ES6 数组处理全指南:从创建、迭代到排序与归并

作者:小括号时间:2026-10-30 21:01:55浏览:134

本文系统梳理 ES6 中处理数组的核心方法。涵盖 Array.from 和 Array.of 的静态创建、keys/values/entries 迭代器转换、fill/copyWithin 填充与复制、join 等转换技巧,以及 push/pop 等栈队列操作。重点解析 sort 排序机制、splice 增删改、indexOf/includes 搜索、find/findIndex 断言查找,以及 forEach/map/filter/every/some 迭代器和 reduce/reduceRight 归并函数的具体用法与参数说明。

ES6 提供了丰富的静态方法用于数组的创建与处理。

Array.from()

该方法旨在将类数组结构或可迭代对象转换为真正的数组实例。

  • 其第一个参数接收一个类数组对象,即任何具备 length 属性且元素可索引的结构,或者是一个可迭代的结构。
  • 第二个参数为可选的映射函数,用于直接增强或转换新数组中的值。
  • 第三个参数同样可选,用于指定映射函数执行时的 this 指向;需要注意的是,箭头函数无法使用此参数。
Array.from({ length: 10 }, (item, index) => index); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.of()

该函数用于将一组参数直接转换为数组。

  • 它主要用于替代 ES6 之前使用 Array.prototype.slice.call(arguments) 这种较为笨拙的方式将 arguments 对象转换为数组的做法。
Array.of((1,2,3,4,5)); //[1, 2, 3, 4, 5]

检测数组类型的方法

instanceof

在单一网页环境(即仅有一个全局作用域)下,使用 instanceof 操作符足以判断数组类型。

value instanceof Array

Array.isArray()

若网页包含多个框架,则可能涉及两个不同的全局执行上下文,进而存在两个不同版本的 Array 构造函数,此时需使用 Array.isArray()。

Array.isArray(value)

ES6 提供的迭代器方法

  • Array 原型上暴露了三个用于检索数组内容的方法:keys()、values() 和 entries()。
  • 由于这些方法均返回迭代器,因此可以利用 Array.from() 将其内容转换为数组实例。
const lazy = ['one', 'two', 'three', 'four'];

keys()

返回一个包含数组索引的迭代器。

Array.from(lazy.keys); //[0, 1, 2, 3]

values()

返回一个包含数组元素的迭代器。

Array.from(lazy.values); //["one", "two", "three", "four"]

entries()

返回一个包含键值对数组元素的迭代器。

Array.from(lazy.entries()); //[[0, "one"][1, "two"][2, "three"][3, "four"]]

ES6 提供的复制和填充方法

Array.fill()

用于向已有数组中插入全部或部分相同的值。

  • 第一个参数指定需要填充的具体值。
  • 第二个参数为开始索引,可选;若未指定则默认从索引 0 开始。
  • 第三个参数为结束索引,可选;若未指定则填充至数组末尾。
  • 若索引为负数,则从数组末尾开始计算;也可将其想象为数组长度加上该负索引得到的正索引。
const zeroes = [0, 0, 0, 0, 0];
 
// 用5填充整个数组
zeroes.fill(5); //[5, 5, 5, 5, 5]
zeroes.fill(0); // 重置
 
// 用6填充索引大于等于3的元素
zeroes.fill(6, 3); //[0, 0, 0, 6, 6]
zeroes.fill(0); // 重置
 
// 用7填充大于等于1且小于3的元素
zeroes.fill(7, 1, 3); //[0, 7, 7, 0, 0]
zeroes.fill(0); // 重置
 
// 用8填充索引大于等于1且小于4的元素
// (-4 + zeroes.length = 1)
// (-1 + zeroes.length = 1)
zeroes.fill(8, -4, -1); //[0, 8, 8, 8, 0]
zeroes.fill(0); // 重置
 
// fill() 静默忽略超出数组边界、零长度及方向相反的索引范围
 
// 索引过低,忽略
zeroes.fill(1, -10, -6); //[0, 0, 0, 0, 0]
 
// 索引过高忽略
zeroes.fill(1, 10, 15); //[0, 0, 0, 0, 0]
 
// 索引反向,忽略
zeroes.fill(2, 4, 2); //[0, 0, 0, 0, 0]
 
// 索引部分可用,填充可用部分
zeroes.fill(4, 3, 10); //[0, 0, 0, 4, 4]

Array.copyWithin()

  • 该方法按指定范围浅复制数组中的部分内容,并将其插入到指定的索引起始位置。
  • 其开始和结束索引的计算方式与 fill() 相同。
  • copyWithin() 会静默忽略超出数组边界、零长度或方向相反的索引范围。
let ints;
reset = () => ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
reset(); //重置
 
// 从inits中复制0开始的内容,插入到索引5的位置
// 在源索引或目标索引到达数组边界时停止
ints.copyWithin(5); //[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
reset(); // 重置
 
// 从ints中复制索引5开始的内容,插入到索引0开始的位置
ints.copyWithin(0, 5); //[5, 6, 7, 8, 9, 5, 6, 7, 8, 9]
reset(); // 重置
 
// 从int中复制索引0开始到索引3结束的内容
// 插入到索引4的位置
ints.copyWithin(4, 0, 3); //[0, 1, 2, 3, 0, 1, 2, 7, 8, 9]
reset(); // 重置
 
// JavaScript 引擎在插值钱回完整复制范围内的值
// 因此复制期间不存在重写的风险 
ints.copyWithin(2, 0, 6); //[0, 1, 0, 1, 2, 3, 4, 5, 8, 9]
reset(); // 重置
 
// 支持负索引值,与fill()相对于数组末尾计算正向索引的过程是一样的
ints.copyWithin(-4, -7, -3); //[0, 1, 2, 3, 4, 5, 3, 4, 5, 6]

数组转化方法

let colors = ['red', 'blue', 'yellow'];

Array.valueOf()

该方法直接返回数组本身。

colors.valueOf(); // ["red", "blue", "yellow"]

Array.toString()

返回由每个值转换为等效字符串后拼接而成的逗号分隔字符串。

colors.toString(); // "red,blue,yellow"

Array.toLocaleString()

  • 返回一个逗号分隔的数组值的字符串表示。
  • 为了生成最终字符串,该方法会调用每个值的 toLocaleString() 方法,而非 toString()。
colors.toLocaleString(); // 'red,blue,yellow'

Array.join()

  • 该方法仅接收一个参数 separator,即分隔符。
  • 它将数组元素组合成一个字符串,以 separator 为分隔符;若省略则默认使用逗号作为分隔符。
let arr = [1, 2, 3];
console.log(arr.join()); // 1,2,3
console.log(arr.join("-")); // 1-2-3
console.log(arr); // [1, 2, 3](原数组不变)

实现重复字符串

利用 join() 方法可实现字符串重复,只需传入目标字符串及重复次数即可返回结果,具体函数如下:

function repeatString(str, n) {
    return new Array(n + 1).join(str);
}
console.log(repeatString("abc", 3)); // abcabcabc
console.log(repeatString("Hi", 5)); // HiHiHiHiHi 

需注意,若数组中包含 null 或 undefined 项,则在 join()、toLocaleString()、toString() 及 valueOf() 的返回结果中,这些项将以空字符串表示。

栈操作方法

push() 和 pop()

  • push():可接收任意数量的参数,将它们逐个添加到数组末尾,并返回修改后数组的长度。
  • pop():从数组末尾移除最后一项,减少数组的 length 值,并返回被移除的项。
const arr = ["Lily","lucy","Tom","lazy"];
const count = arr.push("Jack","Sean");
console.log(count); // 6
console.log(arr); // ["Lily", "lucy", "Tom", "lazy", "Jack", "Sean"]
const item = arr.pop();
console.log(item); // Sean
console.log(arr); // ["Lily", "lucy", "Tom", "lazy", "Jack"]

队列操作方法

shift() 和 unshift()

  • shift():删除原数组的第一项,并返回被删除元素的值;若数组为空则返回 undefined。
  • unshift():将参数添加到原数组开头,并返回数组的新长度。
  • 这组方法与 push() 和 pop() 对应,前者操作数组开头,后者操作数组结尾。
const arr = ["Lily", "lucy", "Tom", "lazy"];
const count = arr.unshift("Jack", "Sean");
console.log(count); // 6
console.log(arr); //["Jack", "Sean", "Lily",  "lucy", "Tom", "lazy"]
const item = arr.shift();
console.log(item); // Jack
console.log(arr); // ["Sean", "Lily", "lucy", "Tom", "lazy"]

排序方法

reverse()

用于反转数组项的顺序。

let arr = [13, 24, 51, 3];
console.log(arr.reverse()); //[3, 51, 24, 13]
console.log(arr); //[3, 51, 24, 13](原数组改变)

sort()

  • 默认按升序排列数组项,即最小值位于最前,最大值位于最后。
  • 排序时,sort() 会调用每个数组项的 toString() 转型方法,然后比较得到的字符串以确定顺序。即使数组项均为数值,sort() 比较的也是字符串,因此可能出现非预期的排序结果。
let arr1 = ["a", "d", "c", "b"];
console.log(arr1.sort()); // ["a", "b", "c", "d"]
let arr2 = [13, 24, 51, 3];
console.log(arr2.sort()); // [13, 24, 3, 51] 两位数字先比较第一位再比较第二位
console.log(arr2); // [13, 24, 3, 51](原数组被改变)

为解决上述问题,sort() 可接收一个比较函数作为参数,以指定值的先后顺序。比较函数接收两个参数。

  • 若第一个参数应位于第二个之前,则返回负数;若两参数相等,返回 0;若第一个参数应位于第二个之后,则返回正数。以下为一个简单的比较函数示例:
function compare(value1, value2) {
    return value1 - value2;
}
let arr = [13, 24, 51, 3];
console.log(arr.sort(compare)); // [3, 13, 24, 51]

若需通过比较函数产生降序排序结果,只需交换比较函数返回值的符号即可:

function compare(value1, value2) {
    return value2 - value1;
}
let arr = [13, 24, 51, 3];
console.log(arr.sort(compare)); // [51, 24, 13, 3]

数组操作方法

Array.concat()

该方法将参数添加到原数组中。它先创建当前数组的副本,然后将接收到的参数添加到副本末尾,最后返回新构建的数组。若未传递参数,它仅复制当前数组并返回副本。

const arr = [1,3,5,7];
const arrCopy = arr.concat(9,[11,13]);
console.log(arrCopy); //[1, 3, 5, 7, 9, 11, 13]
console.log(arr); // [1, 3, 5, 7](原数组未被修改)

从测试结果可见:若传入非数组参数,则直接将其添加到数组后;若传入数组,则将数组中的各项添加到原数组中。但若传入的是二维数组呢?

const arrCopy2 = arr.concat([9,[11,13]]);
console.log(arrCopy2); //[1, 3, 5, 7, 9, Array[2]]
console.log(arrCopy2[5]); //[11, 13]

上述代码中,arrCopy2 数组的第五项是一个包含两项的子数组。这表明 concat 方法仅将传入数组中的每一项作为独立项添加;若传入数组的某项本身是数组,该子数组也会被视为单一项添加到 arrCopy2 中。

Array.slice()

返回从原数组指定开始下标到结束下标之间项组成的新数组。

slice() 可接受一个或两个参数,分别指定要返回项的起始和结束位置。

  • 若仅有一个参数,slice() 返回从该指定位置开始到当前数组末尾的所有项。
  • 若有两个参数,该方法返回起始和结束位置之间的项,但不包括结束位置的项。
const arr = [1,3,5,7,9,11];
const arrCopy = arr.slice(1);
const arrCopy2 = arr.slice(1,4);
const arrCopy3 = arr.slice(1,-2);
const arrCopy4 = arr.slice(-4,-1);
console.log(arr); //[1, 3, 5, 7, 9, 11](原数组没变)
console.log(arrCopy); //[3, 5, 7, 9, 11]
console.log(arrCopy2); //[3, 5, 7]
console.log(arrCopy3); //[3, 5, 7]
console.log(arrCopy4); //[5, 7, 9]
// arrCopy只设置了一个参数,也就是起始下标为1,所以返回的数组为下标1(包括下标1)开始到数组最后。 
// arrCopy2设置了两个参数,返回起始下标(包括1)开始到终止下标(不包括4)的子数组。 
// arrCopy3设置了两个参数,终止下标为负数,当出现负数时,将负数加上数组长度的值(6)来替换该位置的数,因此就是从1开始到4(不包括)的子数组。 
// arrCopy4中两个参数都是负数,所以都加上数组长度6转换成正数,因此相当于slice(2,5)。

Array.splice()

  • splice() 是一个功能强大的数组方法,支持删除、插入和替换操作。
  • 删除操作:可删除任意数量的项,只需指定两个参数:要删除的第一项位置和要删除的项数。例如,splice(0,2) 会删除数组的前两项。
  • 插入操作:可向指定位置插入任意数量的项,只需提供三个参数:起始位置、0(要删除的项数)和要插入的项。例如,splice(2,0,4,6) 会从位置 2 开始插入 4 和 6。 替换操作:可向指定位置插入任意数量的项,同时删除任意数量的项,只需指定三个参数:起始位置、要删除的项数和要插入的任意数量项。插入项数不必等于删除项数。例如,splice(2,1,4,6) 会删除位置 2 的项,然后从位置 2 开始插入 4 和 6。
  • splice() 方法始终返回一个数组,包含从原始数组中删除的项;若未删除任何项,则返回空数组。
let arr = [1,3,5,7,9,11];
let arrRemoved = arr.splice(0,2);
console.log(arr); //[5, 7, 9, 11]
console.log(arrRemoved); //[1, 3]
let arrRemoved2 = arr.splice(2,0,4,6);
console.log(arr); // [5, 7, 4, 6, 9, 11]
console.log(arrRemoved2); // []
let arrRemoved3 = arr.splice(1,1,2,4);
console.log(arr); // [5, 2, 4, 4, 6, 9, 11]
console.log(arrRemoved3); //[7]

搜索和位置方法

严格相等

Array.indexOf() 和 Array.lastIndexOf()

  • indexOf():接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。默认从数组开头(位置 0)向后查找。
  • lastIndexOf():接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。默认从数组末尾向前查找。
  • 这两个方法均返回要查找项在数组中的位置,若未找到则返回 -1。在比较时,它们使用全等操作符(严格相等)。
const arr = [1,3,5,7,7,5,3,1];
console.log(arr.indexOf(5)); //2
console.log(arr.lastIndexOf(5)); //5
console.log(arr.indexOf(5,2)); //2
console.log(arr.lastIndexOf(5,4)); //2
console.log(arr.indexOf("5")); //-1

Array.includes() ES7

  • 第一个参数为要查找的元素。
  • 第二个可选参数为起始搜索位置,默认索引为 0。
  • 该方法返回一个布尔值。
const arr = [1,3,5,7,7,5,3,1];
arr.includes(3); // true
arr.includes(4); // false

断言函数

  • ECMAScript 允许按照定义的断言函数搜索数组,每个索引都会调用该函数。
  • 断言函数的返回值决定了当前索引的元素是否被视为匹配。
  • 第一个参数为元素:数组中当前搜索的元素。
  • 第二个参数是索引:当前元素的索引。
  • 第三个参数是数组本身:正在搜索的数组。

Array.find() 和 Array.findIndex()

  • find() 返回第一个匹配的元素。
  • findIndex() 返回第一个匹配元素的索引。
  • 这两个方法均从数组的最小索引开始搜索。
  • 两者均接收第二个可选参数,用于指定断言函数内部 this 的值。
const people = [
    {
        name: 'lazy',
        age: 25
    },
    {
        name: 'lazy',
        age: 23
    },
    {
        name: 'make',
        age: 20
    }
]
people.find((element, index, array) => element.age > 21); //{name: "lazy", age: 25}
people.findIndex((element, index, array) => element.age > 21); //0

找到匹配项后,这两个方法均不再继续搜索。

迭代方法

Array.forEach()

  • 用于对数组进行遍历循环,对数组中的每一项运行给定函数。
  • 该方法没有返回值。参数均为 function 类型,默认包含传参,分别为:遍历的数组内容、对应的数组索引、数组本身。
const arr = [1, 2, 3, 4, 5];
arr.forEach(function(x, index, a){
console.log(x + '|' + index + '|' + (a === arr));
});
// 输出为:
// 1|0|true
// 2|1|true
// 3|2|true
// 4|3|true
// 5|4|true

Array.map()

  • 意为“映射”,对数组中的每一项运行给定函数,返回由每次函数调用结果组成的新数组。
  • 以下代码利用 map 方法实现数组中每个数求平方。
const arr = [1, 2, 3, 4, 5];
const arr2 = arr.map(function(item){
    return item*item;
});
console.log(arr2); //[1, 4, 9, 16, 25]

Array.filter()

具备“过滤”功能,对数组中的每一项运行给定函数,返回满足过滤条件组成的新数组。

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const arr2 = arr.filter(function(x, index) {
return index % 3 === 0 || x >= 8;
}); 
console.log(arr2); //[1, 4, 7, 8, 9, 10]

Array.every()

判断数组中每一项是否都满足条件,只有所有项均满足条件时,才返回 true。

const arr = [1, 2, 3, 4, 5];
const arr2 = arr.every(function(x) {
return x < 10;
}); 
console.log(arr2); //true
const arr3 = arr.every(function(x) {
return x < 3;
}); 
console.log(arr3); // false

Array.some()

判断数组中是否存在满足条件的项,只要有一项满足条件,即返回 true。

const arr = [1, 2, 3, 4, 5];
const arr2 = arr.some(function(x) {
return x < 3;
}); 
console.log(arr2); //true
const arr3 = arr.some(function(x) {
return x < 1;
}); 
console.log(arr3); // false

归并方法

Array.reduce() 和 Array.reduceRight()

这两个方法均会迭代数组的所有项,然后构建一个最终返回的值。reduce() 从数组的第一项开始逐个遍历到最后;而 reduceRight() 则从数组的最后一项开始向前遍历到第一项。

这两个方法均接收两个参数:

  • 每一项上调用的函数。
  • (可选的) 作为归并基础的初始值。

传给 reduce() 和 reduceRight() 的函数接收 4 个参数:前一个值、当前值、项的索引和数组对象。该函数返回的任何值都会作为第一个参数自动传给下一项。第一次迭代发生在数组的第二项上,因此第一个参数是数组的第一项,第二个参数是数组的第二项。

以下代码使用 reduce() 实现数组求和,数组初始值设为 10。

const values = [1,2,3,4,5];
const sum = values.reduceRight(function(prev, cur, index, array){
return prev + cur;
},10);
console.log(sum); //25

总结

本文介绍了 ES6 处理数组的相关方法,更多相关内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!

作者最新文章