← 中文资源

简体中文版本

with 拷贝数组并按位替换

Array.prototype.with 拷贝数组只换一个下标:负下标从尾部计数、越界抛 RangeError,串联多次调用即可完成交换,源数组始终不动。

阅读英文原文

运行结果

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

["e2e4","e4e5","g1f3"] | source intact: ["e2e4","e7e5","g1f3"]
["g1f3","e7e5","e2e4"]
[1,2,99]
invalid index throws RangeError: true

实现说明

各个操作都建立在顶层绑定之上:copy、rotated。

使用要点

  • 每一步打印都带着自己的标签:invalid index throws RangeError:。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件的状态由几个模块级绑定持有:copy、rotated。

核心语句

const rotated = moves.with(0, moves[2]!).with(2, moves[0]!);
const moves: string[] = ['e2e4', 'e7e5', 'g1f3'];
const copy = moves.with(1, 'e4e5');

代码示例

const moves: string[] = ['e2e4', 'e7e5', 'g1f3'];

// with(index, value):拷贝数组只换一个下标,源不动
const copy = moves.with(1, 'e4e5');
console.log(JSON.stringify(copy), '| source intact:', JSON.stringify(moves));

// 两次 with 串起来就是首尾交换
const rotated = moves.with(0, moves[2]!).with(2, moves[0]!);
console.log(JSON.stringify(rotated));

// 负下标从尾部计数;越界抛 RangeError
console.log(JSON.stringify([1, 2, 3].with(-1, 99)));
try {
  [1, 2, 3].with(7, 0);
} catch (e) {
  console.log('invalid index throws RangeError:', e instanceof RangeError);
}