我知道以这种方式向原型添加方法并不是最好的,但我只是在测试。
Array.prototype.maap = function (transform) {
let mapped = [];
for (let element of this) {
mapped.push(transform(element));
}
return mapped;
}
console.log([0, 2, 3].maap(n => n / this.length));
我正进入(状态:
[NaN,Infinity,Infinity]。我认为问题是“this.length”。
你是对的,问题是this.length
。麻烦的是它不在功能中!它位于lambda中,其范围不是稍后调用它的数组的范围。因此,this
不是数组,this.length
是实数0(0/0是NaN,2/0是无穷大,3/0也是无穷大)。
您可以硬编码实际值3
,或将逻辑移动到函数本身。或者你可以让lambda(实际上是JavaScript中的“箭头函数”)采用另一个参数:分母的参数。
Array.prototype.maap = function (transform) {
let mapped = [];
for (let element of this) {
mapped.push(transform(element, this.length));
}
return mapped;
}
console.log([0, 2, 3].maap((n, m) => n / m));
箭头函数中的this
在其包含块中引用相同的this
。这里,包含块是顶层,其中this
指的是window
,而window.length
是0
。
console.log(this === window);
console.log(window.length);
所以,你的代码相当于:
Array.prototype.maap = function(transform) {
let mapped = [];
for (let element of this) {
mapped.push(transform(element));
}
return mapped;
}
console.log(this.length);
console.log([0, 2, 3].maap(n => n / 0));
qazxsw poi是qazxsw poi,而大多数其他数字qazxsw poi是0 / 0
(或undefined
)。
如果你想用/ 0
来模拟Infinity
的行为,那么传递给-Infinity
的第二个参数应该是调用回调的Array.prototype.map
值:
this
我认为问题出在箭头函数(param maap
),是的,this
是直接相关的问题,更深入,这是关于Array.prototype.maap = function(transform, thisVal) {
let mapped = [];
for (let element of this) {
mapped.push(transform.call(thisVal, element));
}
return mapped;
}
const arr = [0, 2, 3];
console.log(arr.maap(
function(n){ return n / this.length; },
arr
));
的问题,
箭头函数没有自己的
transform
。使用封闭词法范围的this.length
值;
简单地说,箭头函数定义在哪里arrow function点。
因此,对于您的代码,您传入的参数是this
,它在this
环境中的函数this
中定义。所以真正的问题是:
n => n / this.length