我們都知道,你可以做..ES6採用擴展到Concat的多個陣列
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
但是,你怎麼做這個充滿活力的以Concat的ñ陣列? Thx
我們都知道,你可以做..ES6採用擴展到Concat的多個陣列
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
但是,你怎麼做這個充滿活力的以Concat的ñ陣列? Thx
一種選擇是使用reduce
:
let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);
當然,這是一個緩慢的溶液(二次時間)。或者,如果您可以使用Lodash,則_.flatten
完全符合您的要求,並且可以更有效地執行(線性時間)。
編輯
或者,改編自下面Xotic750的評論,
[].concat(...arrs);
這應該是有效的(線性時間)。
一個你有你的陣列在一個數組中,你可以。 'Array.prototype.concat.apply([],arr)'儘管這不再使用擴展運算符。 – Xotic750
@ Xotic750不錯,但你可以使用擴散算子做到這一點!看我的編輯。 –
單獨使用擴展語法無法做到這一點,因爲擴展語法要求您知道預先連接了多少個數組。但是,您可以編寫以下功能:
function concatN(...arguments) {
let accumulator = [];
for(let arg = 0; arg < arguments.length; arg = arg + 1) {
accumulator = [...accumulator, ...arguments[arg]];
}
return accumulator;
}
它可能不會是非常有效的,但(傳播語法的重複使用是O(N²))。使用Array.prototype.concat
會更好。你可以這樣做:
[].concat(all, of, your, arrays);
另一種選擇可能是:
const nArrays = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9],
[10, 11]
];
const flattened = [].concat(...nArrays);
console.log(flattened)
您可以使用for..of
環內傳播元素來連接數組值到一個數組
let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [];
for (let arr of [arr1, arr2 /* , arrN */]) arr3.push(...arr);
console.log(arr3);
你可以使用一個遞歸函數和Array.prototype.concat
const concatN = (x,...xs) =>
x === undefined ? [] : x.concat(concatN(...xs))
console.log(concatN([1,2,3], [4,5,6], [7,8,9]))
// [1,2,3,4,5,6,7,8,9]
你可以使用reduce
和Array.prototype.concat
同樣的事情。這是類似到接受的答案,但在這種情況下
const concatN = (...xs) =>
xs.reduce((x,y) => x.concat(y), [])
console.log(concatN([1,2,3], [4,5,6], [7,8,9]))
// [1,2,3,4,5,6,7,8,9]
let fruits = ["apples", "bananas", "pears"];
let vegetables = ["corn", "potatoes", "carrots"];
let produce = [...fruits, ...vegetables];
console.log(produce);
x.concat(y)
是完全可以接受的(可能快堆)
這個給定的代碼與給定的問題完全相同。這不是爲N個數組製作dynamiclly concat解決方案的答案。 –
您可以將動態數組存儲在數組中...... –
或一個數組作爲值的對象。不可能迭代未知數量的個體變量 – charlietfl
爲什麼你必須使用擴散算子? 'concat'方法仍然有效...... –