写出16个数组常用方法

补充:以下 16 个是 JS 数组(Array.prototype)上最常用的方法,按功能分类整理:

一、增删(会改变原数组)

  1. push(item...) —— 末尾追加,返回新长度。
  2. pop() —— 末尾删除,返回被删元素。
  3. unshift(item...) —— 开头追加,返回新长度。
  4. shift() —— 开头删除,返回被删元素。
  5. splice(start, deleteCount?, item...?) —— 在任意位置增/删/替,返回被删元素数组。
  6. fill(value, start?, end?) —— 用固定值填充一段区间。

二、查询(不改变原数组)

  1. indexOf(item, fromIndex?) / lastIndexOf(item) —— 线性查找首次/末次位置,找不到返回 -1。
  2. includes(item, fromIndex?) —— 是否包含某元素(NaN 也能命中)。
  3. find(callback) / findIndex(callback) —— 按回调查找首个匹配元素/索引。
  4. slice(start?, end?) —— 截取子数组(浅拷贝)。

三、遍历与转换(不改变原数组)

  1. forEach(callback) —— 遍历,无返回值。
  2. map(callback) —— 映射,返回等长新数组。
  3. filter(callback) —— 过滤,返回满足条件的元素组成的新数组。
  4. reduce(callback, initialValue?) / reduceRight —— 累加/折叠为单一值。
  5. some(callback) / every(callback) —— 是否存在/全部满足条件,返回布尔值。
  6. flat(depth?) / flatMap(callback) —— 数组扁平化/扁平化前先 map。

常见用法示例:

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

// 增删改
arr.push(6);            // [1,2,3,4,5,6]
arr.splice(2, 0, 2.5);  // [1,2,2.5,3,4,5,6]

// 查询
arr.indexOf(3);         // 3
arr.includes(99);       // false

// 转换
arr.map(x => x * 2);    // [2,4,5,6,8,10,12]
arr.filter(x => x > 3); // [4,5,6]
arr.reduce((s, x) => s + x, 0); // 28

arr.flat([1,[2,[3]]]);  // [1,2,[3]]

来源整理自:vue3js.cn 面试官系列