js删除数组中的某一个元素

首先可以给JS的数组对象定义一个函数,用于查找指定的元素在数组中的位置,即索引,代码为:

Array.prototype.indexOf = function(val) { 
    for (var i = 0; i < this.length; i++) { 
        if (this[i] == val) return i; 
    } 
    return -1; 
};

然后使用通过得到这个元素的索引,使用js数组自己固有的函数去删除这个元素:

Array.prototype.remove = function(val) { 
      var index = this.indexOf(val); 
            if (index > -1) { 
                  this.splice(index, 1); 
            } 
};

这样就构造了这样一个函数,比如我有有一个数组:

var emp = ['abs','dsf','sdf','fd']

假如我们要删除其中的 'fd' ,就可以使用:

emp.remove('fd');
原文地址:https://www.cnblogs.com/lyzz1314/p/13836673.html