箭头符号:this.forEach不是函数

时间:2017-02-01 02:35:47

标签: javascript function ecmascript-6

在实现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

0 个答案:

没有答案