【记录】js数组

234 阅读1分钟

合并数组array.push.apply()

obj.func.apply(obj,argv)

apply方法的第一个参数是函数运行时所在的作用域,第二个参数是传递给函数的参数,可以是一个数组,同时也可以是arguments对象

var arr1=[1,2];
var arr2=[3,4,5];
arr2.push.apply(arr2,arr1);//[1,2,3,4,5]

调用arr2.push这个函数实例的apply方法,同时把arr1当作参数传入,这样arr2.push这个方法就会遍历arr1数组的所有元素,将arr1的元素存入arr2数组,使arr2数组发生改变。

eg1:

a=[];a.push([1,2,3]),那么你得到的是[[1 2 3]]

[].push.apply(a,[1,2,3]),那么你得到的是[1 2 3]

eg2: 将两个数组合并到一个新数组

const arr1 = [  {    "deleted_at": null  },  {    "created_at": "2021-07-22T05:54:17.000Z",  }];
const arr2 = [  {    "url": "https://music.163.com/#/artist?id=2116",  },  {    "type": 200,  }];

let arry = [];

//方法1:arry.push(...arr1, ...arr2);

//方法2:
arry.push.apply(arry,arr1)
arry.push.apply(arry,arr2)

console.log(arry)

// 打印的值:
[  { deleted_at: null },  { created_at: '2021-07-22T05:54:17.000Z' },  { url: 'https://music.163.com/#/artist?id=2116' },  { type: 200 }]