在寫js代碼時候,有時需要移除數組的元素,在js數組中沒有remove 方法, 不過有splice 方法同樣可以用於移除數組元素:(http://www.w3school.com.cn/jsref/jsref_splice.asp),
splice() 方法向/從數組中添加/刪除項目,然后返回被刪除的項目。
注釋:該方法會改變原始數組。
arrayObject.splice(index,howmany,item1,.....,itemX)
index | 必需。整數,規定添加/刪除項目的位置,使用負數可從數組結尾處規定位置。 |
howmany | 必需。要刪除的項目數量。如果設置為 0,則不會刪除項目。 |
item1, ..., itemX | 可選。向數組添加的新項目。 |
不過 也可以自己擴展數組remove方法..
//擴展 數組remove 方法
//dx為數組下標
Array.prototype.remove = function (dx) {
if (isNaN(dx) || dx > this.length) { return false; }
for (var i = 0, n = 0; i < this.length; i++) {
if (this[i] != this[dx]) {
this[n++] = this[i]
}
}
this.length -= 1
}