# 👉 数组基础

# 数组创建

const array1 = [1, 2, 3];

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

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

# 数组遍历

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

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

for (let item of arr) {}

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

arr.filter((item,index) => {return index > 1});


const initTotal = 0;
const sumArr = arr.reduce((total, curVal, index) => {
  return total + curVal;
}, initTotal)


arr.some(item => item > initTotal);
arr.every(item => item > initTotal);
  • for 循环

    • 最基础的遍历方式,可以控制遍历的起始位置和步长
    • 可以使用 break/continue 控制循环,break 退出循环,continue 跳过此次循环进入下个循环
    • 在非函数环境中,使用 return 会导致语法错误,应使用 break 来退出
    • 在函数内,return 会立即结束当前函数的执行,跳出循环,还会返回函数结果
    • 如果需要结束多层循环,可以使用标签语法
    • 性能较好
  • forEach

    • 不能使用 break/continue
    • 不能使用 return 终止循环
    • 性能次之好
  • for...of

    • ES6新增语法,可以遍历可迭代对象(Array、Set、Map等)
    • 只能获取值,不能获取索引
    • 可以使用 break/continue
  • map

    • 返回新数组,不修改原来数组
    • 常用于数组里的数据变换
  • filter / find

    • 用于数据筛选,返回满足条件的元素组成的新数组
    • 不修改原数组
  • reduce

    • 实现数组的累加、累乘等操作
    • 可以设置初始值
    • 返回单个结果值
  • some/every

    • 用于检查数组元素是否满足条件
    • 返回布尔值

# 常用数组操作方法

# 数组元素的三种方法

# unshift

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

const arr = [1, 2];

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

# push

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

const arr = [1,2];
console.log(arr.push(3), arr); // 3,  [1, 2, 3]

# splice

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

直接修改原有的数组,splice 可用于增加/删除元素,当howmany参数为删除多少个元素,当置为 0, 可从 index 位置增加元素至数组,splice 返回被删除元素对应的数组,增加时返回空数组 []。

const arr = [1, 4];

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

# 删除元素的三种方法

# shift

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

const arr = [1, 2, 3, 4];
console.log(arr.shift(), arr); // 1  [2,3,4]

# pop

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

const arr = [1,2,3,4];
console.log(arr.pop(), arr); // 4, [1,2,3]

# splice

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

  • 直接修改原有的数组,当howmany参数是不为 0 的任意数字 n,可删除数组从 index 开始的 n 个元素,splice 返回被删除元素对应的数组。
  • 如果未规定 howmany 参数,则删除从 index + 1 开始到原数组结尾的所有元素。
const arr = [1, 1.5, 2, 3, 4];

console.log('splice delete 1.5 between 1-2', arr.splice(1, 1), arr); // [1.5], [1,2,3,4]

console.log('splice delete >= 1', arr.splice(1), arr); // [2,3,4], [1]

// 也可以替换
console.log('splice 1.5 -> 2', arr.splice(1, 1, 2), arr) // [1.5], [1,2,2,3,4]

# 分割元素

# slice

arr.slice(start,end)

返回一个新的数组,不修改原数组,包含从 start 到 end (不包括该元素)的数组元素。

const arr = [1,2,3,4,5];

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