简体   繁体   English

从数组中删除元素,知道先前添加的元素数

[英]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? 如果我在javascript中有数组,并且我想要在使用push之前添加多少元素,如何知道它的长度和之前添加的元素数量,如何从数组中删除?

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

By checking the length using length property. 通过使用length属性检查长度。 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. 使用push方法添加元素,并使用splice方法删除基于索引的值,或者使用pop删除顶部元素。

You have to store the length of the array before doing any .push() into: 在执行任何.push()之前,必须存储数组的长度:

  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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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