+ 2
Can someone please explain this loop?
var x = [1, 2, 3, 4, 5]; var count = 0; for (var i = 1; i < 5; i ++) { if (x[i] >i ) count = count + 1; } //it outputs 4 but I'm still yet to figure out why?
3 ответов
+ 1
Hi Duke,
Going through the for loop and the x array starting with i = 1 we have;
x[1] = 2, x[2] = 3 ... x[4] = 5 etc
Each time x[i] is bigger than i
Then because of that the count variable increments by 1. This happens 4 times.
At i = 1; x[1] = 2, 2 > 1 hence count + 1 = 1, count is now 1
"" count + 1 = 2, count is now 2
"" ""
At i = 4; x[4] = 5, 5 > 4 hence count + 1 = 4
+ 2
Thanks a lot Jay. loops & iteration has always been a little bit confusing to me. it's clearer now; thanks.
0
pls can some1 pls explain generics in codes