splice Removes And Inserts In Place
splice returns the removed elements as a typed array, deletes or replaces in place, and index beyond length is a silent no-op on an empty result.
Code
const log: string[] = ['start', 'step1', 'bad', 'step2', 'end'];
// 删除并替换:返回被移除的元素,原数组就地更新
const removed = log.splice(2, 1, 'fixed');
console.log(JSON.stringify(removed), '| now:', JSON.stringify(log), 'length:', log.length);
// 只删除:第二个参数之后省略,被删元素打包成数组
const trimmed = log.splice(1, 2);
console.log(JSON.stringify(trimmed), '| after pure delete:', JSON.stringify(log));
// 下标越过长度:不抛错,返回空数组,原数组不动
const nothing = log.splice(9, 3);
console.log(JSON.stringify(nothing), '| beyond-end no-op:', JSON.stringify(log));Output
Captured from a sandboxed run of this snippet in the build pipeline.
["bad"] | now: ["start","step1","fixed","step2","end"] length: 5
["step1","fixed"] | after pure delete: ["start","step2","end"]
[] | beyond-end no-op: ["start","step2","end"]Watching each part fire
The file’s state is a handful of top-level bindings: removed, trimmed, nothing.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Key statements
const log: string[] = ['start', 'step1', 'bad', 'step2', 'end'];
const removed = log.splice(2, 1, 'fixed');
const trimmed = log.splice(1, 2);
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `removed`, `trimmed`, `nothing`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.