JavaScript 数组
(1)flat():该方法将数组中的所有子数组元素连接成一个新数组。例如:
const arr = [1, [2, [3, [4]], 5]];
const flatArr = arr.flat();console.log(flatArr); // [1, 2, 3, 4, 5]
(2)flatMap():该方法使用给定函数将数组中的每个元素映射为一个新的数组元素,并将所有子数组元素连接成一个新数组。例如:
const arr = [1, [2, [3, [4]], 5]];
const flatArr = arr.flatMap(x => x * 2);
console.log(flatArr); // [2, 4, 6, 8, 10]
(3)sort():该方法对数组元素进行排序,返回一个新的已排序数组。例如:
const arr = [3, 1, 4, 1, 5, 9];
const sortedArr = arr.sort((a, b) => a - b);
console.log(sortedArr); // [1, 1, 3, 4, 5, 9]
copyWithin():该方法在数组中从指定位置开始替换元素,并返回该数组。例如:
let arr = [1, 2, 3];
arr.copyWithin(0, 3); //在索引0的位置开始替换元素,替换3个元素
console.log(arr); // [4, 2, 3]
在这个例子中,我们使用copyWithin()`方法将原数组中的前三个元素替换为[4, 2, x],因此最终输出结果为[4, 2, x]。这个方法不会改变原数组的长度,而是在指定位置上替换元素。注意:这里的第二个参数3表示替换的元素个数,因此不会改变原数组的长度。