给定整数数组,对其中j
的值为j
或=>
<=
的数组执行array.length
操作的最有效方法是什么?
我尝试过类似的事情...
function performJ(arr, j) {
arr.someMethod();
let i = 0;
while (j !== 0) {
if (i < arr.length) {
arr[i] = /* operate on arr[i] */
} else {
// when i reaches arr.length, reset it to continue operations j
i = 0;
arr[i] = /* operate on arr[i] */
}
// increment i, step through arr
++i;
// decrement j as we perform operations on arr
--j;
}
return arr.someMethod();
}
这在很多情况下都有效,但是由于某些原因,arr
和j
的大量输入似乎导致while
循环中的算术运算逐渐消失。
谢谢!
使用模对索引[i % arr.length]
从0到j
进行迭代:
function performJ(arr, j) {
arr.someMethod(); // ?
for (let i = 0; i < j; i++) {
arr[i % arr.length] = /* operation */
}
return arr.someMethod(); // ?
}