← 中文资源

简体中文版本

toSpliced 复制后增删改

用 toSpliced 插入、删除、替换数组元素,返回新数组而不改动原列表。

阅读英文原文

运行结果

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

original: mon,tue,wed,thu,fri
updated: mon,tue,break,wed,thu,fri
without first two: wed,thu,fri
appended: mon,tue,wed,thu,fri,sat
drop last: mon,tue,wed,thu
schedule unchanged: true

实现说明

演示用的数据放在这几个模块级绑定中:schedule、withHoliday、shorter、inserted。

使用要点

  • 演示输出是带标签的(original:、updated:、without first two:),每个操作都会留下自己的一行标注。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 状态都挂在模块顶层:schedule、withHoliday、shorter。

核心语句

const withHoliday = schedule.toSpliced(2, 1, 'break', 'wed');
const schedule = ['mon', 'tue', 'wed', 'thu', 'fri'];
const inserted = schedule.toSpliced(5, 0, 'sat');

代码示例

const schedule = ['mon', 'tue', 'wed', 'thu', 'fri'];

// toSpliced 返回新数组,原数组保持不变
const withHoliday = schedule.toSpliced(2, 1, 'break', 'wed');
console.log('original:', schedule.join(','));
console.log('updated:', withHoliday.join(','));

// 删除:第二个参数是删除数量
const shorter = schedule.toSpliced(0, 2);
console.log('without first two:', shorter.join(','));

// 插入:删除 0 个
const inserted = schedule.toSpliced(5, 0, 'sat');
console.log('appended:', inserted.join(','));

// 负索引从末尾计算
const trimmed = schedule.toSpliced(-1, 1);
console.log('drop last:', trimmed.join(','));

console.log('schedule unchanged:', schedule.length === 5);