欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在JS數(shù)組特定索引處指定位置插入元素的技巧

 更新時間:2014年08月24日 14:52:17   投稿:whsnow  
這篇文章主要介紹了如何在JS數(shù)組特定索引處指定位置插入元素?將一個元素插入到現(xiàn)有數(shù)組的特定索引處,需要的朋友可以參考下

如何在JS數(shù)組特定索引處指定位置插入元素?

需求: 將一個元素插入到現(xiàn)有數(shù)組的特定索引處。聽起來很容易和常見,但需要一點時間來研究它。

// 原來的數(shù)組
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
// 拼接函數(shù)(索引位置, 要刪除元素的數(shù)量, 元素)
array.splice(2, 0, "three"); // 
array; // 現(xiàn)在數(shù)組是這個樣子 ["one", "two", "three", "four"]

如果對擴展原生 JavaScript 不反感,那么可以將這個方法添加到數(shù)組原型(Array prototype)中:

Array.prototype.insert = function (index, item) {
this.splice(index, 0, item);
}; 

此時,可以這樣調(diào)用:

var nums = ["one", "two", "four"];
nums.insert(2, 'three'); // 注意數(shù)組索引, [0,1,2..]
array // ["one", "two", "three", "four"]

相關(guān)文章

最新評論