[英]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.