[英]JavaScript: How to join / combine two arrays to concatenate into one array?
我正在嘗試將 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'
使用現代 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 倍。
對象組合.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 });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.