如何在JS数组特定索引处指定位置插入元素?
需求: 将一个元素插入到现有数组的特定索引处。听起来很容易和常见,但需要一点时间来研究它。
// 原来的数组 var array = ["one", "two", "four"]; // splice(position, numberOfItemsToRemove, item) // 拼接函数(索引位置, 要删除元素的数量, 元素) array.splice(2, 0, "three"); // array; // 现在数组是这个样子 ["one", "two", "three", "four"]
如果对扩展原生 JavaScript 不反感,那么可以将这个方法添加到数组原型(Array prototype)中:
Array.prototype.insert = function (index, item) { this.splice(index, 0, item); };
此时,可以这样调用:
var nums = ["one", "two", "four"]; nums.insert(2, 'three'); // 注意数组索引, [0,1,2..] array // ["one", "two", "three", "four"]
【在JS数组特定索引处指定位置插入元素的技巧】相关文章:
★ TypeError document.getElementById(...) is null错误原因
★ javascript实现dom动态创建省市纵向列表菜单的方法
★ 对联浮动广告效果
★ 强制设为首页代码
★ javascript委托(Delegate)blur和focus用法实例分析