Home >Web Front-end >JS Tutorial >Insert an element at a specified position in a JS array at a specific index_javascript tips
Many array-related tasks sound simple, but this is not always the case, and developers often do not need them. Recently I came across the need to insert an element into an existing array at a specific index. It sounds easy and common, but it takes a little time to research it.
// 原来的数组 var array = ["one", "two", "four"]; // splice(position, numberOfItemsToRemove, item) // 拼接函数(索引位置, 要删除元素的数量, 元素) array.splice(2, 0, "three"); array; // 现在数组是这个样子 ["one", "two", "three", "four"]
If you are not averse to extending native JavaScript, you can add this method to the Array prototype:
Array.prototype.insert = function (index, item) { this.splice(index, 0, item); };
At this time, you can call it like this:
var nums = ["one", "two", "four"]; nums.insert(2, 'three'); // 注意数组索引, [0,1,2..] array // ["one", "two", "three", "four"]