簡體   English   中英

從數組中刪除元素,知道先前添加的元素數

[英]remove elements from array knowing number of previously added elements

如果我在javascript中有數組,並且我想要在使用push之前添加多少元素,如何知道它的長度和之前添加的元素數量,如何從數組中刪除?

//toAdd has for example 10 elements
 $.each(toAdd, function (index, item) {
   myArr.push(item);
  });

通過使用length屬性檢查長度。 使用push方法添加元素,並使用splice方法刪除基於索引的值,或者使用pop刪除頂部元素。

在執行任何.push()之前,必須存儲數組的長度:

  var arrLen = myArr.length;

  //toAdd has for example 10 elements
  $.each(toAdd, function (index, item) {
     myArr.push(item);
  });

現在,如果您想重置它,只需設置長度即可:

myArr.length = arrLen;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM