在实现map时,我注意到在箭头表示法中有类型错误this.forEach
不是函数,而在使用es5函数的情况下运行正常。
Array.prototype.map = function(projectionFunction) {
var results = [];
//Array.foreach is also error
this.forEach( (arrayItem) => {
results.push(projectionFunction(arrayItem));
});
return results;
};
var res = [5,10,15].map((x) => { return x + 2; });
console.log(res);

无效
Array.prototype.map = (projectionFunction) => {
var results = [];
this.forEach( (arrayItem) => {
results.push(projectionFunction(arrayItem));
});
return results;
};
var res = [5,10,15].map((x) => { return x + 2; });
console.log(res);

错误
this.forEach( (arrayItem) => {
^
TypeError: this.forEach is not a function