JavaScript数组原型“this”没有“push”方法
我试过这个:JavaScript数组原型“this”没有“push”方法,javascript,arrays,prototype,Javascript,Arrays,Prototype,我试过这个: // 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 us
// 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的新方法,它可以将数组[1,2,3]传递给该方法,并且每个元素都添加到调用该方法的数组中
例如
var myArr = [1, 2, 3];
myArr.addArr( [4, 5, 6] );
// The output is supposed to be [1, 2, 3, 4, 5, 6]
我得到了未捕获的TypeError:this.push不是一个函数,我已经尝试过调试,它总是返回父数组,但它说push不是一个函数
Array.prototype.addArr = function( arr ){
var that = this;
arr.forEach(function(elm){
that.push( elm );
});
return this;
};
var myArr = [1,2,3];
myArr.addArr([4,5]);
我怎样才能解决它?我可以使用像Lodash这样的库来实现这些功能,但对于这样一个小的应用程序,我不愿意这样做
谢谢 将其存储到函数外部的变量中
Array.prototype.addArr = function( arr ){
var that = this;
arr.forEach(function(elm){
that.push( elm );
});
return this;
};
var myArr = [1,2,3];
myArr.addArr([4,5]);
或者,正如@nnnnnn所指出的,您可以将其作为参数传递给.forEach函数
Array.prototype.addArr = function( arr ){
arr.forEach(function(elm){
this.push( elm );
},this);
return this;
};
var myArr = [1,2,3];
myArr.addArr([4,5]);
将其存储到函数外部的变量中
Array.prototype.addArr = function( arr ){
var that = this;
arr.forEach(function(elm){
that.push( elm );
});
return this;
};
var myArr = [1,2,3];
myArr.addArr([4,5]);
或者,正如@nnnnnn所指出的,您可以将其作为参数传递给.forEach函数
Array.prototype.addArr = function( arr ){
arr.forEach(function(elm){
this.push( elm );
},this);
return this;
};
var myArr = [1,2,3];
myArr.addArr([4,5]);
这对于每个函数都是特定的。forEachfunction…是一个新函数,它具有自己的值…数组。forEach方法在调用回调时不会将其设置为数组。虽然你可以用arr.forEachfunction{},arr.这样做,但是回调向你迭代的同一个数组中添加新元素是没有意义的。哦,我觉得太愚蠢了!我甚至没注意到。非常感谢你们所有人。顺便说一句,通过这个.push.applythis,arr;而不是forEach.this,这是每个函数特有的。forEachfunction…是一个新函数,它具有自己的值…数组。forEach方法在调用回调时不会将其设置为数组。虽然你可以用arr.forEachfunction{},arr.这样做,但是回调向你迭代的同一个数组中添加新元素是没有意义的。哦,我觉得太愚蠢了!我甚至没注意到。非常感谢你们所有人。顺便说一句,通过这个.push.applythis,arr;而不是forEach。@DeepakKamat不客气!:-arr.forEachfunction{},这不是比创建新变量更容易吗?forEach的可选第二个参数指定回调中的值。@nnnnnn这是真的。不确定它是否会对这里的性能产生很大影响,但也许它可以被认为是更干净的解决方案:-我修改了我的答案,添加了这一点,谢谢!是的,任何性能差异都不值得担心。我的意思是更容易,因为打字或思考更少。用this.push.applythis,arr;替换forEach可能会有性能改进;。也许没有。我不知道。@nnnnnn将取决于这个.push.apply的实现。对于非常大的数组,可能会有差异,但我也不知道^^ty@DeepakKamat不客气-arr.forEachfunction{},这不是比创建新变量更容易吗?forEach的可选第二个参数指定回调中的值。@nnnnnn这是真的。不确定它是否会对这里的性能产生很大影响,但也许它可以被认为是更干净的解决方案:-我修改了我的答案,添加了这一点,谢谢!是的,任何性能差异都不值得担心。我的意思是更容易,因为打字或思考更少。用this.push.applythis,arr;替换forEach可能会有性能改进;。也许没有。我不知道。@nnnnnn将取决于这个.push.apply的实现。对于非常大的数组,可能会有差异,但我也不知道^^ty