javaScript 数组即将新增的4个非破坏性方法

354 阅读2分钟

每日一读系列

主要内容

JavaScript数组即将增加4个非破坏性方法:

  • Array.prototype.toReversed() -> Array
  • Array.prototype.toSorted(compareFn) -> Array
  • Array.prototype.toSpliced(start, deleteCount, ...items) -> Array
  • Array.prototype.with(index, value) -> Array

破坏性方法与非破坏性方法

有些数组的方法我们在调用的时候不会改变原始的数组,我们称它们为非破坏性方法,比如我们经常用到的 filter、some、map、find 等方法;一些方法是会改变原数组本身的,比如:sort、reverse、splice 等方法。

示例

  1. toReversed()
const array = ["屠","永","涛"];
// 非破坏性方法
const array1 =  array.toReversed(); // => ["涛","永","屠"]
array; // => ["屠","永","涛"]
// 破坏性方法
const array2 = array.reverse(); // => ["涛","永","屠"]
array; //=> ["涛","永","屠"]
  1. toSorted()
const array = [3, 1, 2];
// 非破坏性方法
const array1 = array.toSorted(); // => [1, 2, 3]
array; // => [3, 1, 2]
// 破坏性方法
const array2 = array.sort(); // => [1, 2, 3]
array; // => [1, 2, 3]
  1. toSpliced()
const array = [1, 2, 3, 4];
// 非破坏性方法
const array1 = array.toSpliced(1, 2, 5, 6, 7); // => [1, 5, 6, 7, 4]
array; // => [1, 2, 3, 4]
// 破坏性方法
const array2 = array.splice(1, 2, 5, 6, 7); // => [1, 5, 6, 7, 4]
array; // => [1, 5, 6, 7, 4]
  1. with() : 需要改变其中一项
const array = [1, 1, 3];
// 非破坏性方法
array.with(1, 2); // => [1, 2, 3]
array; // => [1, 1, 3]
// 破坏性方法
array[1] = 2;
array; // => [1, 2, 3]

polyfill 提案目前还在stage3 阶段,在生产使用最好使用 polyfill。 一个提案从提出到最后被纳入ES新特性,TC39的规范中有五步要走:

  1. stage0(strawman),任何TC39的成员都可以提交。
  2. stage1(proposal),进入此阶段就意味着这一提案被认为是正式的了,需要对此提案的场景与API进行详尽的描述。
  3. stage2(draft),演进到这一阶段的提案如果能最终进入到标准,那么在之后的阶段都不会有太大的变化,因为理论上只接受增量修改。
  4. state3(candidate),这一阶段的提案只有在遇到了重大问题才会修改,规范文档需要被全面的完成。
  5. state4(finished),这一阶段的提案将会被纳入到ES每年发布的规范之中。

更多的TC39提案相关可参看The TC39 process for ECMAScript features

参考资料

点击访问更多文章...