題:將兩個數(shù)組進行合并,如:[a, b, c]和[d, e, f]進行合并變成[a, b, c, d, e, f].
第一種方法
push加展開賦值(...)
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [
{name: '123', age: '123'},
{name: '456', age: '456'}];
let d = [
{name: '789', age: '789'},
{name: '789', age: '789'}];
a.push(...b);
console.log(a);
c.push(...d);
console.log(c);
注??:push()方法的返回值是新數(shù)組的長度奢浑,所以[1, 2, 3].push(...[4, 5, 6]);返回的結(jié)果是6反浓。
第二種方法
forEach+push
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [
{name: '123', age: '123'},
{name: '456', age: '456'}];
let d = [
{name: '789', age: '789'},
{name: '789', age: '789'}];
a.forEach((item) => {
b.push(item);
});
console.log(b);
c.forEach((item) => {
d.push(item);
});
console.log(d);
第三種方法
新數(shù)組+展開賦值(...)
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [
{name: '123', age: '123'},
{name: '456', age: '456'}];
let d = [
{name: '789', age: '789'},
{name: '789', age: '789'}];
let ab = [...a, ...b];
console.log(ab);
let cd = [...c, ...d];
console.log(cd);
第四種
concat
concat是js中Array自帶的一個方法联喘,用起來比較方便维费。
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [
{name: '123', age: '123'},
{name: '456', age: '456'}];
let d = [
{name: '789', age: '789'},
{name: '789', age: '789'}];
let ab = a.concat(b);
console.log(ab);
let cd = c.concat(d);
console.log(cd);
較為推薦后面兩種方法。
當然丹喻,開一個新數(shù)組進行賦值效率更快一些襟铭,畢竟js底層c++數(shù)組都是定長碌奉,擴展js數(shù)組空間其實也是底層開辟新的空間,所以相對來說是更加推薦使用新數(shù)組+展開賦值的方式寒砖。當然你也可以使用foreach加push赐劣,只要你不怕在公司挨打。