在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
当前回答
这是一个函数,通过它可以连接多个数组
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]
其他回答
使用Array.prototype.concat.apply来处理多个数组的连接:
var resultArray = Array.prototype.concat.apply([], arrayOfArraysToConcat);
例子:
var a1 = [1, 2, 3],
a2 = [4, 5],
a3 = [6, 7, 8, 9];
Array.prototype.concat.apply([], [a1, a2, a3]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
其中'n'是数组的个数,可能是数组的数组…
Var答案= _。Reduce (n, function(a, b){返回a.concat(b)})
似乎正确答案在不同的JS引擎中有所不同。以下是我从ninjagecko的答案中链接的测试套件中得到的结果:
[] .concat。apply在Windows和Android的Chrome 83中最快,其次是reduce(慢56%); 循环concat在Mac的Safari 13中是最快的,其次是reduce(大约慢13%); reduce在iOS上的Safari 12中是最快的,其次是循环concat(慢40%); elementwise push在Windows上的Firefox 70中最快,其次是[].concat。应用(速度慢30%)。
用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 >
这是一个函数,通过它可以连接多个数组
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]