ECMAScript 2023 新特性

文章介绍了JavaScript中用于从数组尾部开始查找元素的findLast和findLastIndex方法,以及非破坏性的数组操作,如toReversed、toSorted和toSpliced,这些方法不会改变原数组。同时提到了.with()方法,作为arr[index]=value的非破坏性版本。
摘要由CSDN通过智能技术生成

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']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值