简体   繁体   中英

remove elements from array knowing number of previously added elements

If I have array in javascript and I want how many elements I added before using push how can I remove from array knowing it's lenght and number of elements added before?

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

By checking the length using length property. Use push method to add element and use splice method to remove the values based on the index or use pop to remove top element.

You have to store the length of the array before doing any .push() into:

  var arrLen = myArr.length;

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

Now if you want to reset it, just set the length:

myArr.length = arrLen;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM