[英]How to change variable during for-loop
I ran into a problem with a for-loop in js.我在 js 中遇到了一个 for 循环的问题。 Let me try to explain my issue.让我试着解释一下我的问题。
For example, we have an array例如,我们有一个数组
let arr = [15, 29, 44];
also we have a for
loop我们还有一个for
循环
for (let h = 1; h < 100; h +=10) {
}
I need to iterate over an array inside the loop, so when h
goes bigger than array it continues from the value number.我需要遍历循环内的数组,所以当h
大于数组时,它会从值数继续。
In the end I should get values like: 10, 15, 25, 35, 44, 54...
最后我应该得到如下值: 10, 15, 25, 35, 44, 54...
I'm trying to make a double loop, but it confuses me.我正在尝试制作一个双循环,但这让我感到困惑。
My code:我的代码:
for (let h = 1; h < 100; h +=10) {
for (var i = 0; i < arr .length; i++) {
if(i > h) {
h=i;
}
}
}
Does there better way to do it?有更好的方法吗?
Thanks谢谢
You could take a single loop with a check if h
is greater than a value from the array, then take this value instead.您可以使用单个循环检查h
是否大于数组中的值,然后取该值。
const array = [15, 29, 44], result = []; for (let h = 10, i = 0; h < 100; h +=10) { if (h > array[i]) h = array[i++]; result.push(h); } console.log(...result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.