Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 16:41:16
Original
1577 people have browsed it

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"]
Copy after login

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); 
};
Copy after login

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"]
Copy after login
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template