指定位置插入元素
/**
* 指定位置插入元素
* @param index 添加元素的位置
* @param items 向数组添加的新项目
*/
Array.prototype.insert = function(index, ...items) {
if (isNaN(index)) {
throw new TypeError('请输入数字');
}
this.splice(index, 0, ...items);
};
var array = [1];
array.insert(1, 2, 3, 4); // array: [1, 2, 3, 4]
指定位置删除元素
/**
* 指定位置删除元素
* @param index 添加元素的位置
*/
Array.prototype.insert = function (index) {
if (isNaN(index)) {
throw new TypeError('请输入数字');
}
this.splice(index, 1);
};
var array = [1, 2, 3, 4];
array.insert(0); // array:[2, 3, 4]