array.push.apply to implment' concat'与解释

时间:2016-04-02 12:15:10

标签: javascript

学习反应式编程并封装这段代码,

results.push.apply(results, subArray);

明白申请

完整代码

Array.prototype.concatAll = function() {
    var results = [];
    this.forEach(function(subArray) {
        results.push.apply(results, subArray);
    });

    return results;
};

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

但是当这段代码出现时,让我的脑袋旋转。它几乎正在做concat。有人可以解释一下吗?

非常感谢

2 个答案:

答案 0 :(得分:3)

让我解释一下。

根据apply API的doc第一个参数是this参数,第二个参数是apply应用于调用方法的参数数组。

这段代码是作者的意图吗?

我觉得作者厌倦了从索引中推送每一个值。例如:

var arr = [];
var val = [1,2,3,4];
arr.push(val[0], val[1], val[2], val[3]);

所以他选择使用为他做同样工作的API,它更简洁。

arr.push.apply(arr, val);

解释问题中代码的第二部分:

我想代码意图的作者是连接多维数组。例如,请遵循以下代码:

Array.prototype.concatAll = function() {
    var results = [];
    this.forEach(function(subArray) {
        results.push.apply(results, subArray);
    });

    return results;
};

var arr = [[1,2,3,4],[5,6,7,8]];
console.log(arr.concatAll()); // Prints [1,2,3,4,5,6,7,8]

答案 1 :(得分:2)

some_function 应用 obj ,[ a b c ])

(基本上......)与:

相同

obj some_function a b ,<强> C

这是:&#34;调用&#39; some_function&#39;引用的函数,使用&#39; obj&#39;作为&#39;这个参数&#39;,以及参数列表作为参数&#34;

也就是说,调用该函数(在您的情况下,&#39; push&#39;)就好像它是&#39; obj&#39;的成员一样。 (在你的情况下&#39;结果&#39;)。

有关详细信息,请参阅:Function.prototype.apply

一个可以解决的例子:

var o1 = {
    name: 'First object',
    f: function(a, b ,c) {
           console.log(this, a, b, c);
       }
};
o1.f('Hello', 'World', '!');
var o2 = {
    name: 'Second object'
};
var some_function = o1.f; // This illustrates that the function is not bound to o1...
some_function.apply(o2, ['foo', 'bar', 'baz']);