在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
当前回答
如果你正在通过map/filter/sort等管道输出结果,并且你想连接数组的数组,你可以使用reduce
let sorted_nums = ['1,3', '4,2']
.map(item => item.split(',')) // [['1', '3'], ['4', '2']]
.reduce((a, b) => a.concat(b)) // ['1', '3', '4', '2']
.sort() // ['1', '2', '3', '4']
其他回答
您可以使用jsperf.com站点来比较性能。这是concat的链接。
增加了以下之间的比较:
var c = a.concat(b);
and:
var c = [];
for (i = 0; i < a.length; i++) {
c.push(a[i]);
}
for (j = 0; j < b.length; j++) {
c.push(b[j]);
}
第二款在镀铬的情况下几乎要慢10倍。
concat()方法用于连接两个或多个数组。它不会更改现有数组,只返回已连接数组的副本。
array1 = array1.concat(array2, array3, array4, ..., arrayN);
轻松使用concat函数:
var a = [1,2,3];
var b = [2,3,4];
a = a.concat(b);
>> [1,2,3,2,3,4]
最快的10倍是迭代数组,就像它们是一个数组一样,而不实际连接它们(如果可以的话)。
我很惊讶concat比push稍微快一点,除非测试不公平。
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']; const arr2 = ['j', 'k', 'l', 'i', 'm', 'n', 'o', 'p', 'q', 'r', 's']; const arr3 = ['t', 'u', 'v', 'w']; const arr4 = ['x', 'y', 'z']; let start; // Not joining but iterating over all arrays - fastest // at about 0.06ms start = performance.now() const joined = [arr1, arr2, arr3, arr4]; for (let j = 0; j < 1000; j++) { let i = 0; while (joined.length) { // console.log(joined[0][i]); if (i < joined[0].length - 1) i++; else { joined.shift() i = 0; } } } console.log(performance.now() - start); // Concating (0.51ms). start = performance.now() for (let j = 0; j < 1000; j++) { const a = [].concat(arr1, arr2, arr3, arr4); } console.log(performance.now() - start); // Pushing on to an array (mutating). Slowest (0.77ms) start = performance.now() const joined2 = [arr1, arr2, arr3, arr4]; for (let j = 0; j < 1000; j++) { const arr = []; for (let i = 0; i < joined2.length; i++) { Array.prototype.push.apply(arr, joined2[i]) } } console.log(performance.now() - start);
如果你抽象它,你可以让不加入的迭代更干净,它仍然是原来的两倍:
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']; const arr2 = ['j', 'k', 'l', 'i', 'm', 'n', 'o', 'p', 'q', 'r', 's']; const arr3 = ['t', 'u', 'v', 'w']; const arr4 = ['x', 'y', 'z']; function iterateArrays(arrays, onEach) { let i = 0; while (joined.length) { onEach(joined[0][i]); if (i < joined[0].length - 1) i++; else { joined.shift(); i = 0; } } } // About 0.23ms. let start = performance.now() const joined = [arr1, arr2, arr3, arr4]; for (let j = 0; j < 1000; j++) { iterateArrays(joined, item => { //console.log(item); }); } console.log(performance.now() - start);
你可以看看这个博客,在这里push()和concat()的性能进行了比较。此外,定制函数在特定场景下表现更好。
https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki