Home >Web Front-end >JS Tutorial >Tips for inserting elements at specified positions at specific indexes in JS arrays_javascript tips

Tips for inserting elements at specified positions at specific indexes in JS arrays_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:38:491732browse

How to insert an element at a specified position at a specific index in a JS array?

Requirement: 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