简体   繁体   English

使用JavaScript循环数组并使用splice删除其所有元素?

[英]Looping array in JavaScript and remove all of its element using splice?

I am having an array of object. 我有一个对象数组。 And I am looping every object and performing some operation and again in the end splice that element from that array. 我循环每个对象并执行一些操作,最后再次从该数组中拼接该元素。 But I am not been able to achieve the desired result. 但是我无法达到预期的效果。

Here is what I have tried: 这是我尝试过的:

This is a sample array: 这是一个示例数组:

var arraylist=[{"username":"fzxd","contry":"vxcvxc"}, 
               {"username":"fzxdfsdf","contry":"vxcvxc"},
               {"username":"fsd","contry":"fsdf"},
               {"username":"fsdf","contry":"werr"}];
var l = arraylist.length;

for(var i = 0; i < l; i++)
{
  // For looping the item and doing some operation..
  console.log(arraylist[i].username + " " + arraylist.length);
  arraylist.splice(i,1); //In the end splicing it from the actual arraylist
}

When I run this only get fzxd 4 and fsd 3 printed on my log and not all elements. 当我运行此命令时,只会在日志中显示fzxd 4fsd 3 ,而不是所有元素。 Where I am doing wrong? 我在哪里做错了? Please guide me. 请指导我。 Thanks! 谢谢!

If you splice out the first element, the element that was at the second position is now at the first position, the element at the second position is the third one. 如果拼接出第一个元素,则位于第二个位置的元素现在位于第一个位置,位于第二个位置的元素是第三个。 Therefore you will skip the second one. 因此,您将跳过第二个。 Instead of accessing arraylist[i] take arraylist[0] as well as arraylist.splice(0, 1) . 而不是访问arraylist[i]而是使用arraylist[i] arraylist[0]以及arraylist.splice(0, 1) Or just: 要不就:

  let users = [{ /*...*/ }, /*...*/ ];

  for(const user of users) {
    // do stuff with user
  }

  users = []; // clear array.

on last operation arraylist.length less then index ; 在最后一个操作arraylist.length上less index ;

.splice it's side effect operation and after every calls as a result your index was moved and your array was changed. .splice是副作用操作,因此在每次调用后,您的索引都被移动并且数组被更改。

 var arraylist = [{ "username": "fzxd", "contry": "vxcvxc" }, { "username": "fzxdfsdf", "contry": "vxcvxc" }, { "username": "fsd", "contry": "fsdf" }, { "username": "fsdf", "contry": "werr" }] var l = arraylist.length; for (var i = 0; i < l; i++) { //For looping the item and doing some operation.. console.log(arraylist.length, i) // on last operation arraylist.length less then index //console.log(arraylist[i].username + " " + arraylist.length); arraylist.splice(i, 1); //In the end splicing it from the actual arraylist } 

You can do it like this: 您可以这样做:

var arraylist = [{ "username": "fzxd", "contry": "vxcvxc" }, { "username": "fzxdfsdf", "contry": "vxcvxc" }, { "username": "fsd", "contry": "fsdf" }, { "username": "fsdf", "contry": "werr" }]
for(var i=arraylist.length-1; i>=0; i--)
{
  console.log(arraylist[i].username);
  arraylist.splice(i,1);
}

I hope this meets your requirement. 我希望这符合您的要求。 Thanks! 谢谢!

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

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