实现说明
演示用的数据放在这几个模块级绑定中: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(",")));