JS如何使用原型但使用不带参数的函数为数组创建新方法

JS How to make a new method to an Array using prototype but with a function that takes no parameters

我想用一个名为 square() 的新方法扩展数组,该方法 returns 一个包含所有数字平方的新数组。我尝试制作它,但我想不出一种方法,使函数 不采用任何参数,例如默认的 JS 数组方法 。比如array.reverse() returns 数组倒过来就是不以数组为参数,像这样: array.reverse(array) 这是我的代码:

Array.prototype.square = function(Array){
    let a = []
    for (let num of Array){
        a.push(num**2)
    }
    return a
}

你走对了,可以像这样轻松完成:

Array.prototype.square = function () {
    return this.map((number) => number * number)
}

let a = [1, 2]; // sample array

console.log(a.square()); // prints [1, 4]

我用过地图,这个过程非常简单。请参阅此以获取更多信息:Array Map Function

您可以在函数内部使用 this 关键字,它将引用调用它的数组。

Array.prototype.square = function() {
  return this.map(number => number ** 2)
}

let test = [1, 2, 3]
console.log(test.square())

备案...
(这种添加的方法的名字叫做wrapper)

/* ---  Array.square  wrapper--- */
if (!Array.prototype.square)  // check that the square method does not already exist 
  {
  Array.prototype.square = function(){ return this.map(x=>x**2) } 
  }
let arr1 = [1,2,3,5,7]
  , arr2 = arr1.square()
  ;
console.log('arr1 ->', JSON.stringify( arr1 ))
console.log('arr2 ->', JSON.stringify( arr2 ))

当您向原型添加方法时,object/array 将始终是 this context。所以你可以简单地遍历 this.

(另外:检查该方法是否已存在于原型中通常是件好事,这就是我也包含该代码的原因。)

if (!('square' in Array.prototype)) {
  Array.prototype.square = function() {
    const arr = [];
    for (let i = 0; i < this.length; i++) {
      arr.push(this[i] ** 2);
    }
    return arr;
  }
}

console.log([1, 2, 3].square());

或者,更简单地说,使用 map 来 return 一个新数组。

if (!('square' in Array.prototype)) {
  Array.prototype.square = function() {
    return this.map(el => el ** 2);
  }
}

console.log([1, 2, 3].square());