1、从尾到头搜索数组
在 JavaScript 中,通过 find() 和 findIndex() 查找数组中的值是一种常见做法。不过,这些方法从数组的开始进行遍历:
const array = [{a: 1}, {a: 2}, {a: 3}, {a: 4}, {a: 5}];
array.find(ele => ele.a > 3); // {a: 4}
array.findIndex(ele => ele.a > 3); // 3
如果要从数组的末尾开始遍历,就必须反转数组并使用上述方法。这样做就需要一个额外的数组操作。findLast() 和 findLastIndex() 的就解决了这一问题。提出这两个方法的一个重要原因就是:语义。
使用:
它们的用法和find()、findIndex()类似,唯一不同的是它们是 从后向前 遍历数组,这两个方法适用于数组和类数组。
findLast() 会返回第一个查找到的元素,如果没有找到,就会返回 undefined;
findLastIndex() 会返回第一个查找到的元素的索引。如果没有找到,就会返回 -1;
const array = [{a: 1}, {a: 2}, {a: 3}, {a: 4}, {a: 5}];
array.findLast(ele=> ele.a > 3); // {a: 5}
array.findLastIndex(ele=> ele.a > 3); // 4
array.findLastIndex(ele=> ele.a > 5); // undefined
2、reverse()、sort()、splice()不修改原数组版本
toReversed() 是 reverse() 方法的非破坏性版本:
const arr = ['a', 'b', 'c'];
const result = arr.toReversed();
console.log(result); // ['c', 'b', 'a']
console.log(arr); // ['a', 'b', 'c']
toSorted() 是 sort() 方法的非破坏性版本:
const arr = ['c', 'a', 'b'];
const result = arr.toSorted();
console.log(result); // ['a', 'b', 'c']
console.log(arr); // ['c', 'a', 'b']
toSpliced 是 splice() 方法的非破坏性版本:
const arr = ['a', 'b', 'c', 'd'];
const result = arr.toSpliced(1, 2, 'X');
console.log(result); // ['a', 'X', 'd']
console.log(arr); // ['a', 'b', 'c', 'd']
3、.with()方法
.with()方法的使用形式:.with(index, value),它是 arr[index] = value 的非破坏性版本
const arr = ['a', 'b', 'c'];
const result = arr.with(1, 'X');
console.log(result); // ['a', 'X', 'c']
console.log(arr); // ['a', 'b', 'c']