在JS数组指定位置插入元素

很多与数组有关的任务听起来很简单,但实际情况并不总是如此,而开发人员在很多时候也用不到他。最近我碰到了这样一个需求: 将一个元素插入到现有数组的特定索引处。听起来很容易和常见,但需要一点时间来研究它。

// 原来的数组  

var array = ["one", "two", "four"];  

// splice(position, numberOfItemsToRemove, item)  

// 拼接函数(索引位置, 要删除元素的数量, 元素)  

array.splice(2, 0, "three");  

array;  // 现在数组是这个样子 ["one", "two", "three", "four"]  

如果你对扩展原生 JavaScript 不反感,那么可以将这个方法添加到数组原型(Array prototype)中:

Array.prototype.insert = function (index, item) {

  this.splice(index, 0, item);  

};  

 

var nums = ["one", "two", "four"];  

nums.insert(2, 'three'); // 注意数组索引, [0,1,2..]  

array   // ["one", "two", "three", "four"]  


我对数组也进行过一些其他的修改,可能你已经看过了:

Arrays 非常的有用—— JavaScript中处理某些任务还是比较繁琐…… 必须编写比实际需要的更多的代码(code-heavy)。为了更方便,请收藏本文,或者将这些片段保存到你的工具箱吧!

原文地址:https://www.cnblogs.com/hubl/p/5767191.html