开门见山,JavaScript 数组即将新增 4 个新的非破坏性方法:
.toReversed()
.toSorted()
.toSpliced()
.with()
Change Array by copy 提案
这四个方法来源于新的 Change Array by copy 提案,目前已经处于 stage3阶段,意味着基本上不会再有太大变化了,我们即将在各大浏览器里看到它们的实现。
提案地址:https://github.com/tc39/proposal-change-array-by-copy
数组的破坏性和非破坏性
为啥这个提案叫 Change Array by copy 呢?字面意思就是从副本里改变数组。
这就要说起数组的破坏性和非破坏性方法了:
有些数组的方法我们在调用的时候不会改变原始的数组,我们称它们为非破坏性方法,比如我们经常用到的 filter、some、map、find 等方法,都是不会改变原数组的:
![](https://img.haomeiwen.com/i26082972/73df44bae89259a2.png)
但是,另外有一些方法是会改变原数组本身的,比如:sort、reverse、splice 等方法。
![](https://img.haomeiwen.com/i26082972/2550ddb007991f63.png)
可以看到,原数组和排序后得到的新数组是一样的,说明这个方法改变了原数组。很多时候我们想用这些方法,但是又不想改变原数组,我们可能会先创建一个副本,比如下面这些操作:
![](https://img.haomeiwen.com/i26082972/df0d3daa3bd247b7.png)
几个数组的新方法,就是用来解决这样的问题的。
toSorted()
.toSorted() 是 .sort() 的非破坏性版本:
![](https://img.haomeiwen.com/i26082972/efc7ece694c1586d.png)
下面是个简单的 polyfill:
if (!Array.prototype.toSorted) {
Array.prototype.toSorted = function(compareFn){
return this.slice().sort(compareFn);
};
}
toReversed()
.toReversed() 是 .reverse() 的非破坏性版本:
![](https://img.haomeiwen.com/i26082972/111e8f18bc89a4ee.png)
下面是个简单的 polyfill:
if (!Array.prototype.toReversed) {
Array.prototype.toReversed = function(){
return this.slice().reverse();
};
}
with()
with() 是对数组的某个元素赋值操作的非破坏性版本,比如下面的操作:
![](https://img.haomeiwen.com/i26082972/3e7d0c7e390131d6.png)
下面是个简单的 polyfill:
if (!Array.prototype.with) {
Array.prototype.with = function(index, value){
const copy = this.slice();
copy[index] = value;
return copy;
};
}
toSpliced()
.splice(start, deleteCount, ...items) 方法比其他几个破坏性方法更复杂点:下面是个简单的 polyfill:
它从 start 开始删除 deleteCount 个元素 ;
然后把 items 插入到被删除的位置;
最后返回已删除的元素。
![](https://img.haomeiwen.com/i26082972/ea01ef1195f93d63.png)
.tospliced() 是 .splice() 的非破坏性版本,它会返回原数组变更后的版本,因此我们拿不到被删除的元素:
![](https://img.haomeiwen.com/i26082972/5ec00fff3cf59a65.png)
下面是个简单的 polyfill:
if(!Array.prototype.toSpliced) {
Array.prototype.toSpliced =function(start, deleteCount, ...items){
constcopy =this.slice();
copy.splice(start, deleteCount, ...items);
returncopy;
};
}
polyfill
提案目前还在 stage3阶段,在生产使用最好使用 polyfill:
https://github.com/tc39/proposal-change-array-by-copy/blob/main/polyfill.js
网友评论