2025-04-30

JavaScript通過設置數組的length屬性來截斷數組是惟一一種縮短數組長度的方法.如果使用delete運算符來刪除數組中元素,雖然那個元素變成未定義的,但是數組的length屬性並不改變兩種刪除元素,數組長度也改變的方法.


  <script>
   /*
   *  方法:Array.remove(dx)
   *  功能:刪除數組元素.
   *  參數:dx刪除元素的下標.
   *  返回:在原數組上修改數組
   */


  //經常用的是通過遍歷,重構數組.
  Array.prototype.remove=function(dx)
  {
    if(isNaN(dx)||dx>this.length){return false;}
    for(var i=0,n=0;i<this.length;i++)
    {
        if(this[i]!=this[dx])
        {
            this[n++]=this[i]
        }
    }
    this.length-=1
  }
  a = [1,2,3,4,5];
  alert(“elements: “+a+”
Length: “+a.length);
  a.remove(0); //刪除下標為0的元素
  alert(“elements: “+a+”
Length: “+a.length);


  /*
   *  方法:Array.baoremove(dx)
   *  功能:刪除數組元素.
   *  參數:dx刪除元素的下標.
   *  返回:在原數組上修改數組.
   */


  //我們也可以用splice來實現.


  Array.prototype.baoremove = function(dx)
  {
    if(isNaN(dx)||dx>this.length){return false;}
    this.splice(dx,1);
  }
  b = [1,2,3,4,5];
  alert(“elements: “+b+”
Length: “+b.length);
  b.baoremove(1); //刪除下標為1的元素
  alert(“elements: “+b+”
Length: “+b.length);
  </script>


 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *