简体   繁体   中英

loop through array at certain index

I am trying to create a javascript function that will take in a value that is passed from servlet. Then it will check the array to find the index of that value in the array. Then the loop starts at that index. Once get to the last value of the array, the loop start all over again from the first value of the array. Follow is code for my function:

function Compute(servletValue){
     var computeArray = [0.000001, 0.000003, 0.00001, 0.00003, 0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3];
     var index = computeArray.indexOf(servletValue);
     for(i = 0; i<computeArray.length; i++){
     console.log(computeArray[i]);
   }
}

Thank you in advanced for your help!

I would create a totally new array and then loop through it, since its much simpler to understand. Something like:

function Compute(servletValue){
     var computeArray = [0.000001, 0.000003, 0.00001, 0.00003, 0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3];
     var index = computeArray.indexOf(servletValue);
     const newArray = [...computeArray.slice(index, computeArray.length), ...computeArray.slice(0, index)] // use a better name 
     // use newArray to loop here...
   }
}

I would probably write something like this:

 const rotateTo = (val, allValues) => { const index = allValues .indexOf (val); const pivot = index < 0 ? 0 : index return [...allValues .slice (pivot), ...allValues .slice(0, pivot)] } console .log ( rotateTo (0.003, [0.000001, 0.000003, 0.00001, 0.00003, 0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3]) )

If the index is not found, this acts as a no-op. Otherwise it returns a new array found by slicing the original one from the index forward then from zero to the index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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