← 中文资源

简体中文版本

toSorted 与 with 先拷贝再变更

toSorted、toReversed、with 都是先拷贝再变更:排序、反转、按索引替换都返回新数组,负索引从末尾数起;共享原数组的使用者不会看到任何原地突变。

阅读英文原文

运行结果

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

ranked: 42,67,88,95
source untouched: 88,42,95,67
corrected: 88,50,95,99
reversed: 67,95,42,88
podium: 95,70,67,42 | source: 88,42,95,67

实现说明

scores、ranked、corrected、podium 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 ranked:、source untouched:、corrected:——输出的每一行都能指回产生它的那次调用。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件的状态由几个模块级绑定持有:scores、ranked、corrected。

核心语句

const podium = scores.with(0, 70).toSorted((a, b) => b - a);
const ranked = scores.toSorted((a, b) => a - b);

代码示例

// ES2023 copy-then-change 数组方法:toSorted / toReversed / with
const scores = [88, 42, 95, 67];

// toSorted 返回排序副本;sort 会原地修改共享数组
const ranked = scores.toSorted((a, b) => a - b);
console.log('ranked:', ranked.join(','));
console.log('source untouched:', scores.join(','));

// with(index, value) 替换单个元素并返回新数组,负索引从末尾数
const corrected = scores.with(1, 50).with(-1, 99);
console.log('corrected:', corrected.join(','));

// toReversed 反转副本
console.log('reversed:', scores.toReversed().join(','));

// 链式:先生成新数组再排序,全程不改 source
const podium = scores.with(0, 70).toSorted((a, b) => b - a);
console.log('podium:', podium.join(','), '| source:', scores.join(','));