0
Why the output is 4? May someone explain it to me because i'm stupid as hell..
var arr=[1,2,3,4]; var x=0; for(var y=0; y<arr.length; y++) { if(y%2==0) x+=arr[y]; } document.write(x);
9 odpowiedzi
+ 4
Read it line by line.
the array contains value 1 , 2 , 3 and 4 in elemental order.
In the loop, you notice this : if(y%2==0) , so just find something which divided by 2 gives no leftover. That something , which is a value, would be the element number which will be added into 'x'
+ 2
because 4!<arr.length
+ 2
You got 1 from first run of this loop. Because, (0%2)= 0. So, after the first run of this loop the variable X value should be 1 (x += arr[0]).
+ 1
yes, and that is just 2.
+ 1
Bro i tried to run your code in my machine and you are correct that the output should be 3 but it is displaying 4.
This is unexpected. I never thought that something this simple can be this awesome.
I will try to apply my brain as much as i can and tell you the answer tomorrow
+ 1
Ok Bro I got your Ans
At first run
0%2 == 0
x+=arr[0] which is 1
so x=1
then 2%2 == 0
x+=arr[2] which is 3
so x=4.
0
arr[y]=arr[2], which is 3.. right? that's how i get it.. but it is 4.. how?
0
if you add 5,6 to the array it displays the outpost 9 insted of 8. just can't understand where it finds that 1.
also if the array is only [1,2] the outpost is 1. how?
0
thank you, man. i assumed (and was wrong obviously) that 0%2=2, but of course it is 0, there's no leftover.. what a math mistake.. :-) the rest is pretty clear. thank you once again