简体   繁体   English

在特定索引处循环数组

[英]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.我正在尝试创建一个 javascript 函数,该函数将接收从 se​​rvlet 传递的值。 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.否则,它返回一个新数组,通过从索引向前切片原始数组,然后从零到索引切片。

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

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