JavaScript: 如何连接/组合两个数组以连接到一个数组?

我试图将 javascript 中的两个数组组合成一个。

var lines = new Array("a","b","c");
lines = new Array("d","e","f");

这是一个快速示例,我希望能够组合它们,这样当第二行被读取时,数组中的第四个元素将返回“ d”

我该怎么做?

227777 次浏览
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

使用现代 JavaScript 语法 -扩散算符扩散算符:

const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];


const c = [...a, ...b]; // c = ['a', 'b', 'c', 'd', 'e', 'f']

它也是当今 JavaScript 中连接数组的最快方法。

使用本地 nodejs v16.4进行速度测试。
物体传播速度快3倍。

ObjectCombining.js

export const ObjectCombining1 = (existingArray, arrayToAdd) => {
const newArray = existingArray.concat(arrayToAdd);
return newArray;
};


export const ObjectCombining2 = (existingArray, arrayToAdd) => {
const newArray = [ ...existingArray, ...arrayToAdd ]
return newArray
};

ObjectComposing.SpeedTest.js

import Benchmark from 'benchmark';


import * as methods from './ObjectCombining.js';


let suite = new Benchmark.Suite();


const existingArray = ['a', 'b', 'c'];
const arrayToAdd = ['d', 'e', 'f'];


Object.entries(methods).forEach(([name, method]) => {
suite = suite.add(name, () => method(existingArray, arrayToAdd));


console.log(name, '\n', method(existingArray, arrayToAdd),'\n');
});


suite
.on('cycle', (event) => {
console.log(`🏎  ${event.target}`);
})
.on('complete', function () {
console.log(`\n🏁 ${this.filter('fastest').map('name')} is fastest.\n`);
})
.run({ async: false });

结果 results