← 中文资源

简体中文版本

Array.prototype.with 安全替换单个索引元素

用 Array.prototype.with 在不改动原数组的前提下替换指定索引,支持负索引从尾部定位,索引越界时直接抛 RangeError 而不是制造稀疏空洞。

阅读英文原文

运行结果

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

patched: ["lint","test","bundle","deploy"]
source : ["lint","test","package","deploy"]
tail   : ["lint","test","bundle","publish"]
out-of-bounds: RangeError true

实现说明

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

使用要点

  • 没有锁文件条目,没有版本钉死——除了运行时,文件什么都不需要。
  • 每一步打印都带着自己的标签:patched:、source :、tail :。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件的状态由几个模块级绑定持有:stages、patched、renamedTail。

核心语句

const stages = ['lint', 'test', 'package', 'deploy'];
const renamedTail = patched.with(-1, 'publish');
const patched = stages.with(2, 'bundle');

代码示例

const stages = ['lint', 'test', 'package', 'deploy'];

// Replace at a positive index without mutating `stages`
const patched = stages.with(2, 'bundle');
console.log('patched:', JSON.stringify(patched));
console.log('source :', JSON.stringify(stages));

// Negative indices count backward from the tail
const renamedTail = patched.with(-1, 'publish');
console.log('tail   :', JSON.stringify(renamedTail));

// Unlike `stages[10] = 'x'` (which creates sparse holes), .with() throws RangeError
try {
  stages.with(10, 'overflow');
} catch (err) {
  console.log('out-of-bounds:', err.name, err.message.includes('Invalid index'));
}