xx.push.apply(xx,arguments)为什么要这样写代码,有什么好处吗

看了一个源码,发现是这样写的,不知道用意是什么,感觉是废话

{

_objects: [],

add: function () {
    this._objects.push.apply(this._objects, arguments);
    ....
    return this;
} 

}

回复
阅读 2.9k
5 个回答

目的是把 arguments类数组的项 push进 _objects数组,利用 apply 函数的特点,这是很好的写法。
当然 ES6 的话可以直接利用解构搞定 this._objects.push(...arguments)

为了让this._objects和arguments合并
一般push是插入,这里arguments是个数组, push可以这样实现两个数组合并

var a = [1, 2]
a.push.apply(a, [3])
console.log(a)
[1, 2, 3]
a.push([3])
console.log(a)
[1, 2, 3, [3]]

以下为旧回答,答错了。这么写是为了能够析构多参数。

光看你给的代码是看不出什么情况。
除非你的代码在其他地方对Array.prototype.push进行了重写或者修改,会导致里面的this指向发生改变,才需要在这里特意指定push函数里面的this_objects;

Array.prototype.push没改动的情况下,以下两种代码的执行结果是一样的。
this._objects.push.apply(this._objects, arguments);
this._objects.push(arguments);

arguments

  • js内置的变量
  • es5里面,它代表了一个函数的所有参数
function test() { console.log(arguments) }

test(1,2,3); // => [1, 2, 3]

参考: https://developer.mozilla.org...

apply

  • js内置的方法
  • 可以自定义this和将数组参数转换成一个一个的参数传进去
Array.prototype.push.apply([], [1]) // => [].push(1)

Array.prototype.push.apply([], [1, 2, 3])
// 等同于
// [].push(1,2,3)

参考: https://developer.mozilla.org...

关于你的问题

  • 如果有这样一个需求
  • 要给一个数组,添加一个参数
// 可能会这样实现
var a = [1];
var add = function (param) {
  a.push(param);
}

add(2); // => [1, 2]
  • 现在需求变了
  • 现在要给这个数组传递2个参数
// 可能会这样实现
var a = [1];
var add = function (param) {
  a.push(param);
}

add(2); // => [1, 2]
add(3); // => [1, 2, 3]
// 如果要添加20个.不是要添加20行了?
// 也可能会重构一下代码
var a = [1];
var add = function (params) {
  params.forEach(function (ele) => {
    a.push(ele);
  })
}
a.add([2, 3]) // => [1, 2, 3]

而你说到的例子,就是避免了人肉把参数先转换成数组,再去用循环push

// 等同于
this._objects = this._objects.concat(arguments)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏