For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/stage/4/proposal-change-array-by-copy.md.
  • 简体中文
  • Change Array by Copy S4

    中文标题:通过复制更改数组

    提案概览
    提案速览

    此提案为 Array.prototype 和 TypedArray.prototype 添加了非变异数组方法,例如 toReversed、toSorted、toSpliced 和 with,这些方法返回应用更改后的新副本。其目的是支持不可变风格的编程以及与元组的互操作性。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    注意 此提案已'完成'并已合并到 ECMAScript 规范中。PR

    通过复制更改数组

    Array.prototypeTypedArray.prototype 上提供额外的方法,通过返回包含更改的新副本来实现对数组的更改。

    状态

    此提案目前处于阶段 4

    支持者

    • Robin Ricard (Bloomberg)
    • Ashley Claymore (Bloomberg)

    审查者

    概述

    此提案为 Array.prototype 引入了以下函数属性:

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

    所有这些方法都保持目标数组不变,并返回执行更改后其副本。

    toReversedtoSortedwith 也将添加到类型化数组:

    • TypedArray.prototype.toReversed() -> TypedArray
    • TypedArray.prototype.toSorted(compareFn) -> TypedArray
    • TypedArray.prototype.with(index, value) -> TypedArray

    这些方法随后将可在 TypedArray 的子类上使用。例如:

    • Int8Array
    • Uint8Array
    • Uint8ClampedArray
    • Int16Array
    • Uint16Array
    • Int32Array
    • Uint32Array
    • Float32Array
    • Float64Array
    • BigInt64Array
    • BigUint64Array

    示例

    const sequence = [1, 2, 3];
    sequence.toReversed(); // => [3, 2, 1]
    sequence; // => [1, 2, 3]
    
    const outOfOrder = new Uint8Array([3, 1, 2]);
    outOfOrder.toSorted(); // => Uint8Array [1, 2, 3]
    outOfOrder; // => Uint8Array [3, 1, 2]
    
    const correctionNeeded = [1, 1, 3];
    correctionNeeded.with(1, 2); // => [1, 2, 3]
    correctionNeeded; // => [1, 1, 3]

    动机

    Tuple.prototype 引入了这些函数作为处理 Record & Tuple 中元组不可变性的方式。虽然数组本质上不是不可变的,但这种编程风格可能对处理冻结数组的用户有益。

    此提案尤其使得编写能够交替处理数组和元组的代码变得更加容易。

    Record & Tuple 的关系

    虽然此提案源自 Record & Tuple,但应独立推进。

    如果 Web 兼容性要求如此,此提案中定义的属性名称将被更改。这些更改应反映在 Tuple.prototype 上。

    实现