实现说明
演示用的数据放在这几个模块级绑定中: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));