F
F
Faha19982016-04-12 14:44:21
JavaScript
Faha1998, 2016-04-12 14:44:21

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

}

initially d = 5; as you can see, 0 occurs only 2 times, and it seems like it should output 3, but it continues to decrement to 0
Please point out the error, I don’t see what the problem is at all

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Shvedov, 2016-04-12
@Faha1998

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 question

Ask a Question

731 491 924 answers to any question