← 中文资源

简体中文版本

splice 原地修改而 slice 只读取

slice 只读取区间并返回浅拷贝,原数组不动;splice 在原数组上删除或插入并返回被移除的元素。两者拼写相近、语义相反,混用会破坏共享数据。

阅读英文原文

实现说明

顶层就这几处状态:roster、removed。

使用要点

  • 跑完文件,输出里会留下标记——slice(1, 3) :、after slice :、removed :。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件的状态由几个模块级绑定持有:roster、removed。

核心语句

const removed = roster.splice(1, 2, 'new-hire'); // removes 2 elements at index 1, then inserts
console.log('removed      :', removed.join(','));
const roster = ['ada', 'bob', 'cyd', 'dee'];
roster.splice(0, 0, 'lead');

代码示例

// slice: pure read, returns a shallow copy of [start, end), negative indices counting from the end
const roster = ['ada', 'bob', 'cyd', 'dee'];
console.log('slice(1, 3)  :', roster.slice(1, 3).join(','));
console.log('after slice  :', roster.join(','));

// splice: writes in place, returning an array of the removed elements
const removed = roster.splice(1, 2, 'new-hire'); // removes 2 elements at index 1, then inserts
console.log('removed      :', removed.join(','));
console.log('after splice :', roster.join(','));

// splice(0, 0, x) inserts at an exact position without removing anything
roster.splice(0, 0, 'lead');
console.log('insert at 0  :', roster.join(','));

// negative start: splice(-1, 1) plucks off the last element
console.log('pop via splice:', roster.splice(-1, 1).join(','), '->', roster.join(','));