9 个神奇且超级实用的 JavaScript 数组方法

作者: jie 分类: JavaScript 发布时间: 2025-02-09 10:19

分享一些超级好用但是又很冷门的数组方法

copyWithin

copyWithin 这个方法就是将一个数组里的某些元素,移动到另外一个位置,可以一次性移动多个

用法

const array1 = ['a', 'b', 'c', 'd', 'e'];

// Copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// Expected output: Array ["d", "b", "c", "d", "e"]

// Copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// Expected output: Array ["d", "d", "e", "d", "e"]

兼容性

at

at 是用来寻找对应索引的元素的,允许传入负数,如果是负数,则从后往前找

用法

const arrya1 = [5, 12, 8, 130, 44];

let index = 2;
console.log(`An index of ${index} returns ${arrya1.at(index)}`);
// Expected output: "An index of 2 returns 8"

index = -2;
console.log(`An index of ${index} returns ${arrya1.at(index)}`);
// Expected output: "An index of -2 returns 130"

兼容性

with

with 可以允许你根据索引去修改数组的某个元素,并且返回一个新的数组

用法

const arr = [1, 2, 3, 4, 5];

console.log(arr.with(2, 6));
// [1, 2, 6, 4, 5]

console.log(arr);
// [1, 2, 3, 4, 5]

兼容性

reduceRight

reduceRight 跟 reduce 的唯一区别就是,reduceRight 是从后往前遍历

用法

const array1 = [
	[0, 1],
	[2, 3],
	[4, 5],
];

const result = array1.reduceRight((accumulator, currentValue) => {
	accumulator.concat(currentValue)
})

console.log(result);
// Expected output: Array [4,5,2,3,0,1]

兼容性

findLast

findLast 和 find 的唯一区别在于,findLast 是从后往前找

用法

const array1 = [5, 12, 50, 130, 44]

const found = array1.findLast((element) => element > 45);

console.log(found);
// Expected output: 130

兼容性

toSorted & toReversed & toSpliced

toSorted、toReversed、toSpliced 与 sort、reversed、splice 的区别在于,sort、reversed、splice 这些方法都会改变原数组,而 toSorted、toReversed、toSpliced 不会

兼容性

flatMap

顾名思义,就是 flat + map 的结合体

用法

const array1 = [1, 2, 1]

const result = array1.flatMap((num) => (num === 2 ? [2, 2] : 1));

console.log(result);
// Expected output: [1, 2, 2, 1]

兼容性

发表回复