题:将两个数组进行合并,如:[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()方法的返回值是新数组的长度,所以[1, 2, 3].push(...[4, 5, 6]);返回的结果是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);
第三种方法
新数组+展开赋值(...)
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);
较为推荐后面两种方法。
当然,开一个新数组进行赋值效率更快一些,毕竟js底层c++数组都是定长,扩展js数组空间其实也是底层开辟新的空间,所以相对来说是更加推荐使用新数组+展开赋值的方式。当然你也可以使用foreach加push,只要你不怕在公司挨打。