在特定索引处循环遍历数组

时间:2020-10-08 19:39:30

标签: javascript arrays

我正在尝试创建一个JavaScript函数,该函数将采用从Servlet传递的值。然后它将检查数组以找到该值在数组中的索引。然后循环从该索引开始。一旦到达数组的最后一个值,循环便从数组的第一个值重新开始。以下是我的函数的代码:

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]);
   }
}

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我将创建一个全新的数组,然后遍历它,因为它很容易理解。像这样:

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...
   }
}

答案 1 :(得分:0)

我可能会这样写:

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])
)

如果未找到索引,则此操作为空操作。否则,它将返回一个新数组,该数组是通过将原始数组从索引向前切片然后从零切片到索引而找到的。

相关问题