#JavaScript#从数组中删除指定值(不是指定位置)的元素实现代码

<script type="text/javascript"> Array.p
Array.prototype.indexOf = function(val) { //prototype 给数组添加属性
      for (var i = 0; i < this.length; i++) { //this是指向数组,this.length指的数组类元素的数量
        if (this[i] == val) return i; //数组中元素等于传入的参数,i是下标,如果存在,就将i返回
      }
      return -1; 
    };
    Array.prototype.remove = function(val) {  //prototype 给数组添加属性
      var index = this.indexOf(val); //调用index()函数获取查找的返回值
      if (index > -1) {
        this.splice(index, 1); //利用splice()函数删除指定元素,splice() 方法用于插入、删除或替换数组的元素
      }
    };
    var array = [1, 2, 3, 4, 5];
    array.remove(3);
</script>

对于需要删除的数组,引用 array.remove(val);函数即可array是被删除的数组名val是指定删除的数组中的具体内容 。

猜你喜欢

转载自blog.csdn.net/G_wendy/article/details/81239142
今日推荐