自学内容网 自学内容网

ES6 数组的扩展(十六)

1. Array.from()

特性:从类数组对象或可迭代对象中创建一个新的数组实例。
用法:将类数组对象或可迭代对象转换为数组。

const likeArray = { 0: 'a', 1: 'b', length: 2 };
const arr = Array.from(likeArray);
console.log(arr); // 输出:['a', 'b']

2. Array.of()

特性:创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。
用法:创建一个包含多个参数的数组。

const arr = Array.of(1, 2, 3);
console.log(arr); // 输出:[1, 2, 3]

3. find()

特性:返回数组中满足提供的测试函数的第一个元素的值,否则返回 undefined。
用法:找出数组中满足条件的第一个元素。

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

4. findIndex()

特性:返回数组中满足提供的测试函数的第一个元素的索引,否则返回 -1。
用法:找出数组中满足条件的第一个元素的索引。

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

5. fill()

特性:用一个固定值填充数组中从起始索引到终止索引(不包括)的所有元素。
用法:将数组中一段区域的元素替换为特定值。

const arr = [1, 2, 3, 4];
arr.fill(0, 1, 3);
console.log(arr); // 输出:[1, 0, 0, 0]

6. copyWithin()

特性:将数组的一部分复制到数组的另一个位置。
用法:在数组内部复制元素。

const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3);
console.log(arr); // 输出:[4, 5, 3, 4, 5]

7. 扩展运算符(Spread Operator)…

特性:允许将数组元素展开成单个元素。
用法:在函数调用、数组字面量中使用。

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // 输出:[1, 2, 3, 4, 5]

8. flat() 和 flatMap()

特性:flat() 将数组的嵌套结构扁平化为一个新数组;flatMap() 先映射数组元素,再扁平化。
用法:简化嵌套数组。

const arr = [1, [2, 3], [4, [5, 6]]];
const flatArr = arr.flat();
console.log(flatArr); // 输出:[1, 2, 3, 4, [5, 6]]

const flatMapArr = arr.flatMap(x => Array.isArray(x) ? x : [x]);
console.log(flatMapArr); // 输出:[1, 2, 3, 4, 5, 6]

原文地址:https://blog.csdn.net/qq_35876316/article/details/140456343

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!