Answer the question
In order to leave comments, you need to log in
If reads everything at once in a loop (JS), what to do?
There is an array with numbers
3 2 1 0 0
, I want that for each equality of the variable 0, another variable is decremented
function compareNumeric(a, b) {
if (a > b) return 1;
if (a < b) return -1;
}
var p = [3,2,1,0,0];
p = p.sort(compareNumeric);
var d = 5, n = 5;
var l = 0;
for(var g=p[l];l<n && d > 0;l++){
if(g == 0){
d--;
}
}
Answer the question
In order to leave comments, you need to log in
well, as I see it, in the first part of the loop declaration, the initial conditions are set, they are not recalculated each time the loop is iterated, respectively, your g is always equal to p[l], at that moment l == 0, respectively g == p[0 ] (which is also 0), so the body of the loop runs five times, g is always 0 -> d decrements to zero and the loop stops. I recommend declaring the loop more classically:
for(var i = 0; i < n && d > 0; i++) {
var g = p[i];
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question