← 中文资源

简体中文版本

splice 原位删除与插入

splice 返回由被移除元素组成的数组、在原数组上就地删除或替换;下标越过长度时静默返回空数组,原数据保持不变,不会抛错。splice(2, 1, 'fixed') 把 'bad' 换成 'fixed' 且返回 ['bad'],纯删除省略替换参数只打包被删元素。

阅读英文原文

运行结果

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

["bad"] | now: ["start","step1","fixed","step2","end"] length: 5
["step1","fixed"] | after pure delete: ["start","step2","end"]
[] | beyond-end no-op: ["start","step2","end"]

实现说明

演示用的数据放在这几个模块级绑定中:removed、trimmed、nothing。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 状态都挂在模块顶层:removed、trimmed、nothing。

核心语句

const log: string[] = ['start', 'step1', 'bad', 'step2', 'end'];
const removed = log.splice(2, 1, 'fixed');
const trimmed = log.splice(1, 2);

代码示例

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));