我试图弄清楚以下两个代码段之间的区别。它们都展平了一个子数组数组,并且都输出相同的东西。

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

    return results;
}; // [ [1,2,3], [4,5,6], [7,8,9] ] -> [1, 2, 3, 4, 5, 6, 7, 8, 9]




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

    return results;
}; // [ [1,2,3], [4,5,6], [7,8,9] ] -> [1, 2, 3, 4, 5, 6, 7, 8, 9]


如何申请工作?为什么results必须写两次?

最佳答案

apply是函数的方法,允许传递显式的this参数(可能与函数所属的对象不同)和参数数组。在您的示例中,apply用于接受参数数组的功能,以替代spread operator

09-25 17:09
查看更多