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

时间:2018-12-29 14:14:21

标签: javascript

我有一个对象数组。我循环每个对象并执行一些操作,最后再次从该数组中拼接该元素。 但是我无法达到预期的效果。

这是我尝试过的:

这是一个示例数组:

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
}

当我运行此命令时,只会在日志上打印fzxd 4fsd 3,而不是所有元素。 我在哪里做错了?请指导我。谢谢!

3 个答案:

答案 0 :(得分:1)

如果拼接出第一个元素,则位于第二个位置的元素现在位于第一个位置,位于第二个位置的元素是第三个元素。因此,您将跳过第二个。除了访问arraylist[i],还请访问arraylist[0]arraylist.splice(0, 1)。或者只是:

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

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

  users = []; // clear array.

答案 1 :(得分:0)

在最后一个操作arraylist.length上依次为lessindex

.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
}

答案 2 :(得分:0)

您可以这样做:

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);
}

我希望这符合您的要求。谢谢!