toSpliced Returns A Copy With Edits

Use toSpliced to insert, remove, and replace array elements while returning a new array, leaving the original list untouched.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

Top-level bindings schedule, withHoliday, shorter, inserted hold the demo state — nothing sits inside a function scope.

Using it

The run emits 6 labeled sections — original:, updated:, without first two:, appended:, drop last:, schedule unchanged: — one per step.

Key statements

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

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Its state lives in module-level bindings: `schedule`, `withHoliday`, `shorter`.