JavaScript中不使用splice方法在数组指定位置插入元素且不覆盖内容的方法
不使用splice在数组指定索引插入元素的实现方法
你之前接触的concat只能在数组首尾拼接,只要配合slice把原数组按目标索引切分成两段,就能在中间插入新元素。以下几种方案都可以实现需求,前两种不会修改原数组,无副作用,更推荐使用:
- 方法1:
slice()配合concat()
利用slice切分原数组为「索引前半段」和「索引后半段」,中间拼接要插入的元素即可,全程不修改原数组:
var colors = ["red", "blue"]; var index = 1; var insertElement = "white"; // 生成新数组,原数组保持不变 var newColors = colors.slice(0, index).concat(insertElement, colors.slice(index)); console.log(newColors); // 输出 ["red", "white", "blue"] console.log(colors); // 原数组仍为 ["red", "blue"]
- 方法2:ES6扩展运算符写法
逻辑和第一种完全一致,写法更简洁直观,是目前最常用的实现方式:
var colors = ["red", "blue"]; var index = 1; var insertElement = "white"; var newColors = [...colors.slice(0, index), insertElement, ...colors.slice(index)]; console.log(newColors); // 输出 ["red", "white", "blue"]
- 方法3:手动移动元素(修改原数组场景适用)
如果需要直接修改原数组,可以通过遍历后移指定索引之后的元素,再给对应位置赋值实现,完全不依赖数组拼接类方法:
var colors = ["red", "blue"]; var index = 1; var insertElement = "white"; // 从数组末尾开始遍历,将索引大于目标位置的元素全部后移一位 for (let i = colors.length; i > index; i--) { colors[i] = colors[i-1]; } colors[index] = insertElement; console.log(colors); // 输出 ["red", "white", "blue"]
内容的提问来源于stack exchange,提问作者KokoBear
相关产品推荐
相关产品推荐

