在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
当前回答
用ES6缩短。
new Set([].concat(...Array));
这可以连接并唯一多个数组;
let Array = [ [“vue”,“巴别塔”,“npm”,“杯”,“mysql”,“少”,“laravel”), (“jquery”、“反应”,js, css, wordpress,“html”,“引导”), [“vue”,“巴别塔”,“npm”,“杯”,“mysql”,“少”,“laravel”), (‘角’,‘cms’,‘js’,‘css’,‘graphql’,‘nodejs ', ' php '], (“severless”、“无头”、“js”,“css”,“设计”,“ps”,“php”), ] const Boom = new Set([].concat(…数组)); //不需要 let dStr = "; Boom.forEach (e = > { dStr += e + ' '; }) document . write(下游); < div class = "结果" > < / div >
其他回答
用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);
这是一个函数,通过它可以连接多个数组
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]
如果你正在通过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']
如果要连接两个以上的数组,为了方便和可能的性能,concat()是最好的方法。
var a = [1, 2], b = ["x", "y"], c = [true, false];
var d = a.concat(b, c);
console.log(d); // [1, 2, "x", "y", true, false];
对于仅连接两个数组,可以使用push接受多个由要添加到数组的元素组成的参数来将元素从一个数组添加到另一个数组的末尾,而无需生成新数组。对于slice(),它也可以用来代替concat(),但这样做似乎没有性能优势。
var a = [1, 2], b = ["x", "y"];
a.push.apply(a, b);
console.log(a); // [1, 2, "x", "y"];
在ECMAScript 2015及以后的版本中,可以进一步简化为
a.push(...b)
然而,对于大型数组(100,000成员的数量级或更多),将元素数组传递给push(使用apply()或ECMAScript 2015展开操作符)的技术可能会失败。对于这样的数组,使用循环是更好的方法。详情见https://stackoverflow.com/a/17368101/96100。
你可以看看这个博客,在这里push()和concat()的性能进行了比较。此外,定制函数在特定场景下表现更好。
https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki