+ 2
Could you Explain this code for me?
var arr = [2,4,6]; var x=1; for(var j=0; j<arr.length; j++){ x+=arr[j]; } alert(x); //output is 13
5 Respostas
+ 2
Safaa Alnabhan
because the for-loop goes throw all elements of the array 'arr' and adds them to x
+ 5
The code sums all items in the array plus 1, the initial value of x.
+ 3
More descriptively, the program increases x by the sum of all elements of arr and alerts this final value of x, i.e., 1+2+4+6 = 13.
+ 3
Its all derived from step-by-step analysis of the code. Try to run the code in your brain, logically deducing what the compiler/interpreter would have done.
See, the for loop selects all the members of arr, one by one, and increments each value into x. That is it add all the elements to x one by one.
+ 2
How did you know that we have to get the sum of all elements?