在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
当前回答
这样解决。
let arr = [[1, 2], [3, 4], [5, 6]];
console.log([].concat(...arr));
其他回答
[].concat.apply([], [array1, array2, ...])
效率证明:http://jsperf.com/multi-array-concat/7
Tim Supinie mentions in the comments that this may cause the interpreter to exceed the call stack size. This is perhaps dependent on the js engine, but I've also gotten "Maximum call stack size exceeded" on Chrome at least. Test case: [].concat.apply([], Array(300000).fill().map(_=>[1,2,3])). (I've also gotten the same error using the currently accepted answer, so one is anticipating such use cases or building a library for others, special testing may be necessary no matter which solution you choose.)
如果你有一个数组的数组,想要连接到一个数组的元素,尝试以下代码(要求ES2015):
let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = [];
for (let arr of arrOfArr) {
newArr.push(...arr);
}
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
或者如果你喜欢函数式编程
let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = arrOfArr.reduce((result,current)=>{
result.push(...current);
return result;
});
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
或者使用ES5语法更好,没有展开操作符
var arrOfArr = [[1,2,3,4],[5,6,7,8]];
var newArr = arrOfArr.reduce((result,current)=>{
return result.concat(current);
});
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
如果你不知道不,这种方法很方便。数组的。
你可以用这个-
let array2d = [[1, 2, 3], [5, 4], [7, 8]];
let array1d = array2d.reduce((merged, block) => {
merged.push(...block);
return merged;
}, []);
console.log(array1d); // [1, 2, 3, 5, 4, 7, 8]
或者从上面的一个答案中我喜欢这个-
let array2d = [[1, 2, 3], [5, 4], [7, 8]];
console.log([].concat(...array2d)); // [1, 2, 3, 5, 4, 7, 8]
或者我发现的这个
let array2d = [[1, 2, 3], [5, 4], [7, 8]];
console.log(array2d.join().split(',').map(Number); // [1, 2, 3, 5, 4, 7, 8]
这是一个函数,通过它可以连接多个数组
function concatNarrays(args) {
args = Array.prototype.slice.call(arguments);
var newArr = args.reduce( function(prev, next) {
return prev.concat(next) ;
});
return newArr;
}
的例子,
console.log(concatNarrays([1, 2, 3], [5, 2, 1, 4], [2,8,9]));
将输出
[1,2,3,5,2,1,4,2,8,9]
用Push合并数组:
Const array1 = [2,7,4]; Const array2 = [3,5,9]; array1.push(…array2); console.log (array1)
使用Concat和Spread运算符: Const array1 = [1,2]; Const array2 = [3,4]; //方法1:Concat Const combined1 =[]。concat (array1 array2); //方法二:Spread Const combined2 =[…]array1……array2); console.log (combined1); console.log (combined2);