实现说明
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(','));