ES6中的数组及对象扩展

mac2026-04-11  3

一、 数组扩展

1. Array.from

作用:将类数组对象转换为数组参数:类数组对象或可遍历对象(iterable)返回:数组Tips:参数一定要有length参数,否则会得到空数组 let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 }; // ES5转换 let arr1 = [].slice.call(arrayLike); // ["a", "b", "c"] // ES6转换 let arr2 = Array.from(arrayLike); // ["a", "b", "c"] // String转换 let string = "string"; let arr3 = Array.from(string); // ["s", "t", "r", "i", "n", "g"] // 一些非正常转换 // 参数为正常数组时,返回一样的数组 let arr4 = Array.from([1, 2, 3]); // [1, 2, 3] // 参数为只有length的数组 let arr5 = Array.from({ length: 3 }); [undefined, undefined, undefined] // 参数为Number时,返回空数组 let arr6 = Array.from(123); // []

2. Array.of

作用:将一组值转换为对象参数:多个值返回:数组Tips:使用Array.of()代替Array()或 new Array(),它返回值统一 let obj = { "a": 1 } let arr1 = Array.of(1, null, "3", undefined, Symbol(), false, obj); // [1, null, "3", undefined, Symbol(), false, {"a": 1}] // Array在只有一个参数且为Number时,会创建相应长度的empty数组 let arr2 = Array(3); // [empty × 3] let arr3 = Array.of(3); // [3]

3. copyWithin

作用:将制定位置的值复制到其他位置参数:(3个参数都应为Number,如果不是则自动转换) target(必选):从该index开始替换start(可选):从该index开始读取想要复制的数据,默认为0,负值为则从尾部开始end(可选):到该index结束读取数据,默认为数组长度,负值为则倒数 返回:数组 let arr1 = [1, 2, 3, 4, 5].copyWithin(1, -2, -1); // [1, 4, 3, 4, 5]

4. find

作用:查找第一个符合条件的数组成员并返回回调函数的参数: value:当前值index:当前索引arr:原数组 返回:数组成员 let arr1 = Array.of(1, null, "3", undefined, Symbol(), false, NaN); arr1.find((n) => n == "3"); // "3" // 可以进行相应判断 arr1.find((n) => typeof(n) == "boolean"); // false // 配合Object.is可以找到NaN,解决IndexOf方法的不足 arr1.find((n) => Object.is(NaN, n)); // NaN // 当查找一个不存在的值时,返回underfined arr1.find((n) => n == "4"); // undefined

5. findIndex

作用:查找第一个符合条件的数组成员并返回索引回调函数的参数: value:当前值index:当前索引arr:原数组 返回:索引 let arr1 = [1, null, "3", undefined, Symbol(), false, NaN]; arr1.findIndex((n) => n == "3"); // 2 // 可以进行相应判断 arr1.findIndex((n) => typeof(n) == "boolean"); // 5 // 配合Object.is可以找到NaN,解决IndexOf方法的不足 let aaaaa = arr1.findIndex((n) => Object.is(NaN, n)); // 6 // 当查找一个不存在的值时,返回underfined let aaa = arr1.findIndex((n) => n == "4"); // -1

 6. fill

作用:用定制填充数组,用于空数组初始化等回调函数的参数: value:填充的值start:开始填充的indexend:结束填充的index 返回:数组 ["a", "b", "c", "d", "e"].fill(6, 1, -1); // ["a", 6, 6, 6, "e"]

7. entries、keys、values

作用:用于遍历数组entries:对键值对的遍历keys:对键名的遍历values:对键值的遍历 let arr = ["a", "b", "c"]; for (let [index, elem] of arr.entries()){ console.log(index, elem); } // 0 "a" // 1 "b" // 2 "c" for (let index of arr.keys()){ console.log(index); } // 0 // 1 // 2 for (let elem of arr.values()){ console.log(elem); } // a // b // c

8. includes

作用:查找某个数组中是否包含该值回调函数的参数: value:需要查找的值index(可选):查找开始的索引位置,默认从0开始 返回:true or false let arr1 = Array.of(1, null, "3", undefined, Symbol(), false, NaN); arr1.includes(1) // true arr1.includes(NaN) // true arr1.includes("3", 2) // true arr1.includes("3", 4) // false

9. 

二、 对象扩展

最新回复(0)