看了一个源码,发现是这样写的,不知道用意是什么,感觉是废话
{
_objects: [], add: function () { this._objects.push.apply(this._objects, arguments); .... return this; }
}
看了一个源码,发现是这样写的,不知道用意是什么,感觉是废话
{
_objects: [], add: function () { this._objects.push.apply(this._objects, arguments); .... return this; }
}
为了让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);
js
内置的变量es5
里面,它代表了一个函数的所有参数function test() { console.log(arguments) }
test(1,2,3); // => [1, 2, 3]
参考: https://developer.mozilla.org...
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]
// 可能会这样实现
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
16 回答2.9k 阅读✓ 已解决
6 回答4.3k 阅读✓ 已解决
7 回答1.8k 阅读
14 回答2k 阅读
3 回答1k 阅读✓ 已解决
2 回答6.5k 阅读✓ 已解决
4 回答854 阅读✓ 已解决
目的是把 arguments类数组的项 push进 _objects数组,利用 apply 函数的特点,这是很好的写法。
当然 ES6 的话可以直接利用解构搞定
this._objects.push(...arguments)