原文日期: 2014年07月24日
翻译日期: 2014年07月26日
翻译人员: 铁锚
很多与数组有关的任务听起来很简单,但实际情况并不总是如此,而开发人员在很多时候也用不到他。最近我碰到了这样一个需求: 将一个元素插入到现有数组的特定索引处。听起来很容易和常见,但需要一点时间来研究它。
// 原来的数组
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
// 拼接函数(索引位置, 要删除元素的数量, 元素)
(2, 0, "three");
array; // 现在数组是这个样子 ["one", "two", "three", "four"]
如果你对扩展原生 JavaScript 不反感,那么可以将这个方法添加到数组原型(Array prototype)中:
= function (index, item) {
(index, 0, item);
};
此时,可以这样调用:
var nums = ["one", "two", "four"];
(2, 'three'); // 注意数组索引, [0,1,2..]
array // ["one", "two", "three", "four"]
我对数组也进行过一些其他的修改,可能你已经看过了:
- Remove an Item From an Array : 从数组中删除元素
- Clone Arrays : 数组克隆
- Empty Arrays : 空数组
- Sort Arrays : 数组排序