findLast, findLastIndex
获取数组中最后一个匹配的元素或者元素索引
const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);
console.log(found);
// Expected output: 130
虽然感觉使用常见不多,但是想想要是遇到需要查找反方向第一个的常见,真没有什么性能ok又优雅的方式了
浏览器都是新版本才开始支持
已被babel plugin: babel-plugin-polyfill-es-shims支持
toReversed toSorted toSpliced
reverse sort splice的不改变原数组,返回处理过的新数组版本
const original = [1, 2, 3, 4];
const reversed = original.toReversed();
console.log(original);
// [ 1, 2, 3, 4 ]
console.log(reversed);
// [ 4, 3, 2, 1 ]
const original = [1, 3, 2, 4];
const sorted = original.toSorted();
console.log(original);
// [ 1, 3, 2, 4 ]
console.log(sorted);
// [ 1, 2, 3, 4 ]
const original = [1, 4];
const spliced = original.toSpliced(1, 0, 2, 3);
console.log(original);
// [ 1, 4 ]
console.log(spliced);
// [ 1, 2, 3, 4 ]
应该是非常实用了,平时写Array的链式调用时,碰到这几个都得分开了写,有了这些返回引用的函数版本,写起来就更流畅了。
都是高版本浏览器才开始支持
已被babel plugin: babel-plugin-polyfill-es-shims支持
with
这里是Array.prototype.with。使用方式为:
array.with(index, value)
返回一个新数组,不改变原数组 将原数组的第index项变为value返回。
const original = [1, 2, 2, 4];
const withThree = original.with(2, 3);
console.log(original);
// [ 1, 2, 2, 4 ]
console.log(withThree);
// [ 1, 2, 3, 4 ]
额感觉这样的场景挺少的。
补充一点: toReversed toSorted toSpliced with都是浅拷贝