这两段代码有什么区别?(JavaScript)

What is the difference between these two bits of code? (javascript)

本文关键字:区别 什么 JavaScript 两段 代码      更新时间:2023-09-26

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

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 运算符的替代品。