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

时间:2010-10-20 06:12:56

标签: javascript arrays

我正在尝试将javascript中的2个数组合并为一个。

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

这是一个快速示例,我希望能够将它们组合起来,以便在读取第二行时,数组中的第4个元素将返回“d”

我该怎么做?

3 个答案:

答案 0 :(得分:273)

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'

答案 1 :(得分:0)

使用现代 JavaScript:

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

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

答案 2 :(得分:-1)

使用本地 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
};

ObjectCombining.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