簡體   English   中英

如何按順序從數組中獲取元素?

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

在您看來,我的問題似乎既簡單又愚蠢,但我自己能夠解決。

我有數組x

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

還有一個變量y從數組中隨機獲取元素:

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

然后我在另一個 function 中使用y

現在我需要依次從數組中取出元素(第一個 x[0]、x[1] 等)並將它們傳遞給另一個 function。

也就是說,我需要一個類似的變量,如y ,它將按順序傳遞數組元素。

如何實施? 通過櫃台?

感謝您的任何幫助。

創建一個副本並使用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