# 👉 数组基础

# 数组创建

const array1 = [1, 2, 3];

// 传参n代表长度,会初始化长度为n的空元素数组
// 不传参数 等价于 array2 = []
const array2 = new Array(n);

// 如果填充的是引用类型,会填充入参的引用
const arry3 = new Array(7).fill(1);

# 数组遍历

for (let i = 0; i < arr.length; i++) {}

arr.forEach((item, index) => {});

arr.map((item, index) => {});

for (let item of arr) {
}

# 常用数组操作方法

# 数组增加元素的三种方法

# unshift

直接修改原有的数组,添加元素到数组的头部,并返回数组长度。

const arr = [1, 4];

console.log(arr.unshift(2), arr); // 3  [2, 1, 4]

# push

直接修改原有的数组,添加元素到数组的尾部,并返回数组长度。

# splice

arrayObject.splice(index,howmany,item1,.....,itemX)

直接修改原有的数组,splice 可用于增加/删除元素,当howmany参数至为 0 可增加元素至数组指定位置,splice 返回被删除元素的值。

const arr = [1, 4];

console.log(arr.splice(1, 0, 2, 3), arr); // []  [1, 2, 3, 4]

# 删除元素的三种方法

# shift

直接修改原有的数组,删除数组的第一个元素,并返回这个被删除的元素值。

const arr = [1, 4];

console.log(arr.shift(), arr); // 1  [4]

# pop

直接修改原有的数组,删除数组尾部的元素,并返回这个被删除的元素值。

# splice