返回

ES6 数组的扩展新增:提升数组的处理能力

前端

  1. Array.from():将类似数组对象转换为数组

Array.from()方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历的对象(iterable object)。

1.1 类似数组对象

类似数组对象是指具有length属性和可以按索引访问的元素的对象,但它不是真正的数组。例如,字符串、类数组(arguments对象)、NodeList对象等都是类似数组对象。

使用Array.from()方法可以轻松地将类似数组对象转换为真正的数组。

const string = 'Hello';
const arrayFromSting = Array.from(string);
console.log(arrayFromSting); // 输出:['H', 'e', 'l', 'l', 'o']

const argumentsArray = Array.from(arguments);
console.log(argumentsArray); // 输出:[1, 2, 3, 4, 5]

const nodeList = document.querySelectorAll('li');
const arrayFromNodeList = Array.from(nodeList);
console.log(arrayFromNodeList); // 输出:[li, li, li, li, li]

1.2 可遍历对象

可遍历对象是指可以被循环遍历的对象,例如,字符串、Set、Map、Generator对象等都是可遍历对象。

使用Array.from()方法可以将可遍历对象转换为真正的数组。

const set = new Set([1, 2, 3, 4, 5]);
const arrayFromSet = Array.from(set);
console.log(arrayFromSet); // 输出:[1, 2, 3, 4, 5]

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const arrayFromMap = Array.from(map);
console.log(arrayFromMap); // 输出:[['a', 1], ['b', 2], ['c', 3]]

const generator = function* () {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
};
const arrayFromGenerator = Array.from(generator());
console.log(arrayFromGenerator); // 输出:[1, 2, 3, 4, 5]

2. Array.of():创建新的数组

Array.of()方法用于创建一个新的数组,可以接受任意数量的参数,这些参数将成为新数组的元素。

Array.of()方法与Array.from()方法的主要区别在于:

  • Array.of()方法创建的数组的长度是固定的,即它不会随着元素的添加或删除而改变。
  • Array.of()方法创建的数组的元素是原始值,而Array.from()方法创建的数组的元素可以是任何对象。
const array1 = Array.of(1, 2, 3, 4, 5);
console.log(array1); // 输出:[1, 2, 3, 4, 5]

const array2 = Array.of('Hello', 'World', '!');
console.log(array2); // 输出:['Hello', 'World', '!']

const array3 = Array.of(undefined, null, true, false);
console.log(array3); // 输出:[undefined, null, true, false]

3. 扩展运算符(...):展开数组

扩展运算符(...)可以将一个数组展开为一组单独的元素,并插入到另一个数组中。

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const newArray = [...array1, ...array2];
console.log(newArray); // 输出:[1, 2, 3, 4, 5, 6]

扩展运算符也可以用于将一个数组复制到另一个数组中。

const array1 = [1, 2, 3];
const array2 = [...array1];
console.log(array2); // 输出:[1, 2, 3]

4. find() 和 findIndex() 方法:查找数组中的元素

find()方法用于查找数组中第一个符合指定条件的元素,并返回该元素。如果找不到符合条件的元素,则返回undefined。

const array = [1, 2, 3, 4, 5];
const foundElement = array.find(element => element > 3);
console.log(foundElement); // 输出:4

findIndex()方法用于查找数组中第一个符合指定条件的元素的索引,并返回该索引。如果找不到符合条件的元素,则返回-1。

const array = [1, 2, 3, 4, 5];
const foundIndex = array.findIndex(element => element > 3);
console.log(foundIndex); // 输出:3

5. includes() 方法:检查数组中是否包含指定元素

includes()方法用于检查数组中是否包含指定元素,如果包含则返回true,否则返回false。

const array = [1, 2, 3, 4, 5];
const isIncluded = array.includes(3);
console.log(isIncluded); // 输出:true

总结

ES6数组的扩展新增为JavaScript数组提供了更简单、更灵活的方式来创建、转换和操作数组。这些新增的方法使数组处理变得更加高效和易于管理。