js从数组中删除指定元素


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

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


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

猜你喜欢

转载自blog.csdn.net/weixin_41637749/article/details/83827056
今日推荐