简体   繁体   English

如何按顺序从数组中获取元素?

[英]How can I sequentially take elements from an array?

My question seems to you to be easy and stupid, but I was able to solve it myself.在您看来,我的问题似乎既简单又愚蠢,但我自己能够解决。

I have array x :我有数组x

let x = [
    {"ID":"123456"},
    {"ID":"789456"},
    {"ID":"303099"},
    {"ID":"300446"},
    {"ID":"300234"}
];

And There is the variable y that randomly takes elements from an array:还有一个变量y从数组中随机获取元素:

let y = x[Math.floor(Math.random() * x.length)];

Then I use y in another function.然后我在另一个 function 中使用y

Now I need to sequentially take the elements from the array (first x[0], x[1], etc.) and pass them to another function.现在我需要依次从数组中取出元素(第一个 x[0]、x[1] 等)并将它们传递给另一个 function。

That is, i need a similar variable like y , which will pass the array elements sequentially.也就是说,我需要一个类似的变量,如y ,它将按顺序传递数组元素。

How can this be implemented?如何实施? through the counter?通过柜台?

Thank you for any help.感谢您的任何帮助。

Create a copy and use Array.shift to extract the elements from that in a loop:创建一个副本并使用Array.shift从循环中提取元素:

 let x = [ {"ID":"123456"}, {"ID":"789456"}, {"ID":"303099"}, {"ID":"300446"}, {"ID":"300234"} ]; // create a copy let copy = [...x]; // loop it while(copy.length) { const x = copy.shift(); doSomethingWithX(x); console.log(`[copy] now ${JSON.stringify(copy)}`); } function doSomethingWithX(x) { console.log(`Here's [x.ID] for you ${x.ID}`) }

for (const el of x) {
  yourFunction(el);
}

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

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