DIV CSS 佈局教程網

JavaScript concat 與 apply 合併數組的方法解析
編輯:關於JavaScript     

concat 的基本用法

concat 常用來合併陣列。它會把新元素或新陣列的成員接到原陣列尾端,並回傳一個新陣列,原陣列不會被修改。

console.log([].concat([1], [2], [3])); // [1, 2, 3]
console.log([].concat([[1], [2], [3]])); // [[1], [2], [3]]

為什麼需要 apply

如果要把多維陣列攤平,單純使用 concat 可能只能合併最外層。搭配 apply 可以把陣列中的每個元素作為參數傳入。

const flatten = function (arr) {
  return [].concat.apply([], arr);
};

console.log(flatten([[1], [2], [3]])); // [1, 2, 3]

concat 與 apply 的差異

console.log([].concat([[1], [2], [3]])); // [[1], [2], [3]]
console.log([].concat.apply([], [[1], [2], [3]])); // [1, 2, 3]

差異在於:concat 直接接收陣列時,會把該陣列當成一個整體;而 apply 會把外層陣列拆成多個參數,讓 concat 逐一處理。

另一種攤平寫法

也可以使用 reduce 逐步合併:

const flatten = function (array) {
  return array.reduce(function (result, current) {
    return result.concat(current);
  }, []);
};

總結

  • concat 會回傳新陣列,不會修改原陣列。
  • apply 可把陣列轉為函式參數。
  • 兩者搭配時,可以實現淺層攤平。
  • 若需要更深的攤平,仍需自行處理多層結構。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved