簡體   English   中英

這兩位代碼有什么區別? (javascript)

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

我試圖弄清楚以下兩個代碼段之間的區別。 它們都展平了一個子數組數組,並且都輸出相同的東西。

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運算符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM