简体   繁体   English

Javascript 数组循环遍历数组中的特定索引

[英]Javascript Array Loop through specific indexes in array

I'm working in JavaScript native project where I have a huge array with 50k elements (json objects).我在 JavaScript 原生项目中工作,我有一个包含 50k 个元素(json 对象)的巨大数组。
When i loop through this array it take a huge time > 2h当我遍历这个数组时,需要花费大量时间 > 2h

for(var i = 1; i <= myArray.length; i++) {
// my code here for each element
}

So what I plan to do is loop through specific indexes in array:所以我打算做的是遍历数组中的特定索引:

// loop one from index 0 to 10k

// loop one from index 10k to 20k

...

Each loop I will make it in a separate process每个循环我都会在一个单独的过程中完成

If you're just wanting to loop through specific indexes, would this work?如果您只是想遍历特定索引,这可行吗?

Using Math.min ensures that even when progressing in 10k increments, you never exceed the length of the array.使用Math.min可确保即使以 10k 增量进行,也不会超过数组的长度。 With an array of 24736 items, the first loop would run from 0 to 9999, the second loop would run from 10000 to 19999, and the third loop would run from 20000 to 24736.对于包含 24736 个项目的数组,第一个循环将从 0 运行到 9999,第二个循环将从 10000 运行到 19999,第三个循环将从 20000 运行到 24736。

for(let i = 0; i < Math.min(myArray.length, 10000); i++) {
    // ...
}
for(let i = 10000; i < Math.min(myArray.length, 20000); i++) {
    // ...
}
for(let i = 20000; i < Math.min(myArray.length, 30000); i++) {
    // ...
}

You can even nest these loops to perform actions between each loop, like this:您甚至可以嵌套这些循环以在每个循环之间执行操作,如下所示:

 const myArray = Array(54723).fill(); for (let n = 0; n < myArray.length; n += 10000) { for(let i = 0; i < Math.min(myArray.length, 10000); i++) { //... } console.log(Math.min(myArray.length, n + 10000)); }

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

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