当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解js删除数组中的指定元素

详解js删除数组中的指定元素

2018年11月05日  | 移动技术网IT编程  | 我要评论

本篇文章将会给大家介绍两种删除数组中的指定元素的方式,分别为:

1、单独定义一个的函数,通过函数来删除指定数组元素。

2、为array对象定义了一个removebyvalue的方法,在调用方法来删除指定数组元素,调用非常简单的。

下面我们通过简单的代码示例来简单介绍这两种删除数组指定元素的方式。

1、定义单独的函数removebyvalue来进行元素删除

代码示例:删除数组somearray里的"tue"元素

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
 </head>
 
 <body>
  <div class="demo">
   <p>数组:mon, tue, wed, thur</p>
   <p class="p"></p>
 
  </div>
 
 </body>
 
 <script type="text/javascript">
  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"
 
  document.write("<p>新数组:" + somearray + "</p>");
 </script>
 
</html>

效果图:

2、定义并调用数组的removebyvalue方法来删除指定元素

代码示例:删除数组somearray里的"wed"元素

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <div class="demo">
      <p>数组:mon, tue, wed, thur</p>
      <p>删除指定元素"tue"后:</p>
    </div>
  </body>
  <script type="text/javascript">
    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("wed");
    //somearray will now have "mon", "wed", "thur"
 
    document.write("<p>新数组:" + somearray + "</p>");
  </script>
 
</html>

效果图:

总结:以上就是本篇文章所介绍的js删除数组指定元素的两种方式,大家可以自己动手试试,加深理解,希望能对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网