网络编程
位置:首页>> 网络编程>> JavaScript>> js从数组中删除指定值(不是指定位置)的元素实现代码

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

作者:jingxian  发布时间:2024-04-16 10:28:26 

标签:js,删除,数组,指定

引用自百度知道里面的一个问答

例如数组{1,2,3,4,5}

要把数组里面的3删除得到{1,2,4,5}

js代码:


<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.prototype.indexOf = function(val) {
     for (var i = 0; i < this.length; i++) {
       if (this[i] == val) return i;
     }
     return -1;
   };
Array.prototype.remove = function(val) {
     var index = this.indexOf(val);
     if (index > -1) {
       this.splice(index, 1);
     }
   };

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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com