【问题标题】:What is the difference between these two bits of code? (javascript)这两段代码有什么区别? (javascript)
【发布时间】:2016-01-16 00:03:58
【问题描述】:

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

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要写两次?

【问题讨论】:

    标签: javascript arrays apply


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2012-09-22
      • 2021-12-17
      • 1970-01-01
      相关资源
      最近更新 更多