我已经试过这样:JavaScript的数组原型,“这个”没有“推”的方法
// You can pass an array on the addArr method, and each element from the
// passed array is pushed to the array on which addArr was called.
Array.prototype.addArr = function(arr){
console.log(this);
// As `this` is the array, we use this.push to insert arr's elements
arr.forEach(function(elm){
this.push(elm);
});
// And then finally return this.
return this;
};
的代码已经被使用注释解释,但让我把直。我试图在名为addArr
的Array
对象上创建一个新方法,该方法可以将数组[1, 2, 3]
传递给该方法,并将每个元素添加到调用该方法的数组中。
对于e.g
var myArr = [1, 2, 3];
myArr.addArr([4, 5, 6]);
// The output is supposed to be [1, 2, 3, 4, 5, 6]
我越来越Uncaught TypeError: this.push is not a function
,我试图调试,这总是返回父阵列还是它说,push
不是一个函数。
我该如何解决?我可以使用像Lodash这样的库,但我不喜欢这样的小应用程序。
谢谢!
'this'是特定于每个功能。 'forEach(function()...)'是一个新的函数,它有自己的'this'值... – deceze
当你调用你的回调函数时,'.forEach()'方法不会*设置'this'。尽管你可以用'arr.forEach(function(){},arr)'来实现。此外,它真的*没有意义的回调添加一个新的元素到你正在迭代的同一个数组。 – nnnnnn
哦,我觉得很愚蠢!甚至没有注意到这一点。非常感谢你们所有人。 –