今天聊聊最新的JavaScript提案。开门见山,JavaScript数组即将新增四个无损方法:toReversed()toSorted()toSpliced()with()ChangeArraybycopyproposal这四个方法来自于新的ChangeArraybycopyproposal,即目前处于stage3阶段意味着基本上不会有太大变化,我们很快就会看到它们在各大浏览器中的实现。提案地址:https://github.com/tc39/proposal-change-array-by-copy数组的破坏性和非破坏性为什么这个提案叫ChangeArraybycopy?字面意思就是从副本中改变数组。这是关于数组的破坏性和非破坏性方法:有些数组方法我们调用的时候不会改变原来的数组,我们称之为非破坏性方法,比如我们经常用到的filter,map,find等methods不会改变原始数组:但是,还有其他方法会改变原始数组本身,例如:sort,reverse,splice等方法。可以看到原数组和排序后得到的新数组是一样的,说明这个方法改变了原数组。很多时候我们想使用这些方法,又不想改变原来的数组,我们可能会先创建一个副本,比如下面的操作:constsorted1=array1.slice().sort();constsorted2=[...array1].sort();constsorted3=Array.from(array1).sort();几个数组的新方法被用来解决这样的问题。toSorted().toSorted()是.sort()的非破坏性版本:constarray=['c','o','n','a','r','d','l','i'];constresult=array.toSorted();console.log(result);//['a','c','d','i','l','n','o','r']console.log(array);//['c','o','n','a','r','d','l','i']下面是一个简单的polyfill:if(!Array.prototype.toSorted){Array.prototype.toSorted=function(compareFn){returnthis.slice().sort(compareFn);};}toReversed().toReversed()是.reverse()的非破坏性版本:constarray=['c','o','n','a','r','d','l','我'];常量结果=数组。toReversed();控制台日志(结果);//['i','l','d','r','a','n','o','c']console.log(array);//['c','o','n','a','r','d','l','i']这是一个简单的polyfill:if(!Array.prototype.toReversed){Array.prototype.toReversed=function(){returnthis.slice().reverse();};}with()with()是对数组元素赋值操作的非破坏性版本,比如下面的操作:array[index]=value如果我们只是想得到一个新的数组而不不想改变原来的数组,我们可以这样使用:constarray=['c','o','n','a','r','d','l','i'];常量结果=array.with(0,'ConardLi')console.log(result);//['ConardLi','o','n','a','r','d','l','i'];console.log(array);//['c','o','n','a','r','d','l','i']这是一个简单的polyfill:if(!Array.prototype.with){Array.prototype.with=function(index,value){constcopy=this.slice();复制[索引]=值;返回副本;};}toSpliced()。splice(start,deleteCount,...items)方法比其他几种破坏性方法更复杂:它从start开始删除deleteCount个元素;然后在删除的位置插入项目;最后返回被删除的元素常量数组=[1,2,3,4,5,6];常量结果=数组。拼接(1、2、0);安慰。日志(结果);//[2,3]控制台。日志(数组);//[1,0,4,5,6].tospliced()是.splice()的非破坏性版本,它返回原始数组的变异版本,因此我们不会得到删除的元素:constarray=[1,2,3,4,5,6];常量结果=数组。拼接(1、2、0);安慰。日志(结果);//[1,0,4,5,6]console.log(array);//[1,2,3,4,5,6]这是一个简单的polyfill:if(!Array.prototype.toSpliced){Array.prototype.toSpliced=function(start,deleteCount,...items){constcopy=this.slice();copy.splice(开始,deleteCount,...items);返回副本;};}polyfill提案仍处于第3阶段,最好用于生产polyfill:https://github.com/tc39/proposal-change-array-by-copy/blob/main/polyfill.js
