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