简体   繁体   English

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

[英]JavaScript: How to join / combine two arrays to concatenate into one array?

I'm trying to combine 2 arrays in javascript into one.我正在尝试将 javascript 中的 2 个数组合并为一个。

var lines = new Array("a","b","c");
lines = new Array("d","e","f");
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'

Using modern JavaScript syntax - spread operator :使用现代 JavaScript 语法 - 扩展运算符

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

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

It is also the fastest way to concatenate arrays in JavaScript today.它也是当今 JavaScript 中连接数组的最快方式。

Speed test using local nodejs v16.4.使用本地 nodejs v16.4 进行速度测试。
Object Spread is 3x faster.对象传播速度快 3 倍。

ObjectCombining.js对象组合.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 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 });

Result结果结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM