下面的代码使用了两种方式删除数组的元素,第一种定义一个单独的函数,第二种为Array对象定义了一个removeByValue的方法,
定义函数removeByValue进行元素删除:
function removeByValue(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
break;
}
}
}
var somearray = ["mon", "tue", "wed", "thur"]
removeByValue(somearray, "tue");
//somearray will now have "mon", "wed", "thur"
为数组对象增加相应的的方法,调用就变得更加简单了,直接调用数组的removeByValue方法即可删除指定元素:
Array.prototype.removeByValue = function(val) {
for(var i=0; i<this.length; i++) {
if(this[i] == val) {
this.splice(i, 1);
break;
}
}
}
var somearray = ["mon", "tue", "wed", "thur"]
somearray.removeByValue("tue");
//somearray will now have "mon", "wed", "thur"

分类:JS/JQuery, 前端笔记
标签:JavaScript, JS