js 每年新语法总结(部分)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值