實例如下:
複製代碼代碼如下:
/**
* 通過值刪除數組元素
*
* @param mixed value 元素值
* @returns array
*/
Array.prototype.deleteValue = function(value){
var i = 0;
for(i in this){
if(this[i] == value) break;
}
return this.slice(0, i).concat(this.slice(parseInt(i, 10) + 1));
}
//示例
var test = new Array(1,5,3,4,2);
//輸出5
console.log(test.length);
//刪除值為4的元素
test = test.deleteValue(4);
//輸出[1, 5, 3, 2]
console.log(test);
//輸出4
console.log(test.length);
/**
* 通過索引刪除數組元素
*
* @param int index 元素索引
* @returns array
*/
Array.prototype.deleteIndex = function(index){
return this.slice(0, index).concat(this.slice(parseInt(index, 10) + 1));
}
//示例
var test = new Array(1,5,3,4,2);
//輸出5
console.log(test.length);
//刪除索引為1的元素
test = test.deleteIndex(1);
//輸出[1, 3, 4, 2]
console.log(test);
//輸出4
console.log(test.length);