ECMAScript 2023 正式发布
从头到尾搜索数组:findLast() 、findLastIndex() 目前主流浏览器都已经支持了这两个新方法
findLast() 会返回第一个查找到的元素,如果没有找到,就会返回 undefined;
findLastIndex() 会返回第一个查找到的元素的索引。如果没有找到,就会返回 -1
const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}];
array.findLast(elem => elem.v > 3); // {v: 5}
array.findLastIndex(elem => elem.v > 3); // 4
array.findLastIndex(elem => elem.v > 5); // undefined
通过副本更改数组:toReversed()、toSorted()、toSpliced()、with() 目前,主浏览器都已经支持这四个方法:
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']
.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']