【问题标题】:JavaScript: How to join / combine two arrays to concatenate into one array?JavaScript:如何加入/组合两个数组以连接成一个数组?
【发布时间】:2011-04-27 20:56:15
【问题描述】:

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

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

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

我该怎么做?

【问题讨论】:

  • 同样的问题,更多(详细)答案:stackoverflow.com/questions/1584370
  • @David 所有简单的问题都有更多的答案,因为更多的人用谷歌搜索它们(或 ::shivers:: 使用网站的内置搜索功能)。
  • @ignis 这不是重复的。该问题专门询问如何删除结果数组中的重复项。它更具体,这个问题更笼统。

标签: javascript arrays


【解决方案1】:
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'

【讨论】:

  • @Matt 是的,因为它只是一个数组,它不会跟踪其内容。
  • @geotheory 检查 underscorejs 有一个用于 underscorejs.org 的 reduce 函数;)
  • 旧帖,但对于现在在谷歌上搜索的人来说,@geotheory 的问题有一个简单的答案:Array.prototype.concat.apply([], [[1,2],[3,4],[5,6]])
  • es6 : c=a.push(...b)
  • 你也可以这样做: const newArr = [...arr1, ...arr2];
【解决方案2】:

使用现代 JavaScript 语法 - spread operator:

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

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

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

【讨论】:

    【解决方案3】:

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

    结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-04
      • 2021-09-20
      • 2018-11-17
      • 1970-01-01
      • 2016-11-12
      相关资源
      最近更新 更多