Home  >  Article  >  Web Front-end  >  Insert an element at a specified position in a JS array at a specific index_javascript tips

Insert an element at a specified position in a JS array at a specific index_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:41:161552browse

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"]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn