0

Can anyone be good to explain this code properly i always get confused and mix up with things like that ?

what is the output of this code ? var arr = [4,3,2,5]; for var (i=1; i<3 ; i++){ arr[i]=arr[i-1]+arr[i+1]; } alert (arr);

19th Apr 2017, 7:43 PM
Ionut Marian
Ionut Marian - avatar
2 Respuestas
+ 4
arr[0]=4 arr[1]=3 arr[2]=2 arr[3]=5 in the for loop i is 1 and then 2 when i is 1 arr[1]=arr[0]+arr[2] arr[1] =4+2 arr[1]=6 when i is 2 arr[2]=arr[1]+arr[3] arr[2] =6+5 arr[2]=11 after the operations arr[0]=4 arr[1]=6 arr[2]=11 arr[3]=5 output will be 4,6,11,5 edit: if you didn't miss a comma in the array and the 3rd element of the array is really 25, then you have to go for the answer of the chinese user, as mine doesn't solve your problem in that case.
19th Apr 2017, 8:00 PM
seamiki
seamiki - avatar
+ 2
this code result will be 4,29,NaN I think your problem will be why have NaN because if the I = 2 arr[2] = arr[1] +arr[3]; whick arr[3] is out of range, so js will return NaN if it detect the out of range array instead show error.
19th Apr 2017, 7:56 PM
黃冠融
黃冠融 - avatar