简体   繁体   中英

for loop with multiple conditions not working (JS)

I'm trying to make this loop work in order to get the multiples of 5 that are below 1000 in an array (yeah, just getting started with euler), but it keeps crashing my console:

var multiploCincoArray = []; 

for(i = 1, r = i * 5; r < 1000; i++) {
    multiploCincoArray.push(r);
}
console.log(multiploCincoArray);

I know there's something wrong with the stopping condition but i can't seem to find it.

I know i can do this too:

var multiploCincoArray = []; 

for(i = 1; i <= 199 ; i++) { 
    multiploCincoArray.push(5 * i);
}
console.log(multiploCincoArray);

but i want to follow the path shown in the first script (if possible)...

You could move the calculation into the conditional part.

 var multiploCincoArray = []; for (var i = 1, r; r = i * 5, r < 1000; i++) { multiploCincoArray.push(r); } console.log(multiploCincoArray); 

Try that :

var multiploCincoArray = []; 

for(i = 5; i <= 1000; i = i + 5) { 

    multiploCincoArray.push(i);
}
console.log(multiploCincoArray);
 for(i = 1, r = i * 5; r < 1000; i++){

Is the same as:

 i = 1, r = i * 5

 while(r < 1000) i++;

So actually you set r just once (to 5), then you increase i as long as r is smaller than 1000, but as r doesn't change the loop is infinite and crashes your browser.

You might just do:

 for(let i = 5; i < 1000; i += 5)

Your approach doesn't seem right imo.

Firstly start with a single variable i , and iterate till 1000.

for (var i=1; i<1000; i++)

check if the i is a multiple of 5 via i%5 , if it is then push the value in an array.

 var array = []; for (var i=1; i<1000; i++) { if (i%5 === 0) { array.push(i); } } console.log(array); 

On the right track but condition in the wrong place. Change for(i = 1, r = i * 5; r < 1000; i++) to for(i = 1, r=5; r < 1000; r=i*5,i++)

Should use let i and let r for scope but I left it out for clarity.

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