← 中文资源

简体中文版本

复制方法返回新数组 toSorted toReversed toSpliced

toSorted/toReversed/toSpliced/with 都返回新数组且不动源;fill 就地变更需先克隆;flat/flatMap 永远分配新数组,共享状态的管线不再需要先克隆再改。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

sorted copy: [ 1, 1, 3, 4, 5 ]
base intact: [ 3, 1, 4, 1, 5 ]
reversed copy: [ 5, 1, 4, 1, 3 ]
spliced copy: [ 3, 9, 1, 5 ]
base still intact: [ 3, 1, 4, 1, 5 ]
with(0, 99): [ 99, 1, 4, 1, 5 ]
filled clone: [ 3, 1, 0, 0, 0 ] source: [ 3, 1, 4, 1, 5 ]
flat: [ 1, 2, 3 ]
flatMap: [ 'a', 'b', 'c' ]

实现说明

演示用的数据放在这几个模块级绑定中:base、padded。

使用要点

  • 每一步打印都带着自己的标签:sorted copy:、base intact:、reversed copy:。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 状态都挂在模块顶层:base、padded。

核心语句

const padded = structuredClone(base);

代码示例

// Array methods mutate in place; their copies are for pipelines that must not.
const base = [3, 1, 4, 1, 5];

// sort with a numeric comparator sorts ascending; without one it compares as strings
console.log("sorted copy:", base.toSorted((a, b) => a - b));
console.log("base intact:", base);

// reverse has a copying twin; splice's twin is toSpliced
console.log("reversed copy:", base.toReversed());
console.log("spliced copy:", base.toSpliced(1, 2, 9));
console.log("base still intact:", base);

// with() replaces one index and returns a fresh array
console.log("with(0, 99):", base.with(0, 99));

// fill mutates in place, so clone first when the source must survive
const padded = structuredClone(base);
padded.fill(0, 2);
console.log("filled clone:", padded, "source:", base);

// flat/flatMap never mutate: they always allocate a new array
console.log("flat:", [1, [2, [3]]].flat(2));
console.log("flatMap:", ["a,b", "c"].flatMap((s) => s.split(",")));