+ 2

Diference between arr[2] and arr[i/2]

i have this code: var arr = [4, 2, 10, 5]; for (var i =0; i<arr.length;i++){ arr[i] *= i; } alert(arr[i/2]); the output is 20, If it was alert(arr[2]); is 20 too. why? sorry, my english is very poor.

8th Jun 2018, 11:33 AM
Felipe Medeiros
Felipe Medeiros - avatar
2 Réponses
+ 7
Felipe Medeiros No problem 😊 inside the for loop when i=0 arr[0] becomes 0 ie 4*0=0 when i=1 arr[1] becomes 2 when i=2 arr[2] becomes 20 when i=3 arr[3] becomes 15 when i=4 it fails to satisfy the given condition. So now i=4 So when alert arr[i/2] it is actually arr[2] (4/2=2) so the output is 20
8th Jun 2018, 11:39 AM
Mohammad Amir Aqeel
Mohammad Amir Aqeel - avatar
+ 2
because array.length is 4. after the loop i=array.length=4 and therefore i/2=4/2=2 so alert(array[i/2]) is the same as alert(array[2]) for this array
8th Jun 2018, 11:35 AM
Max
Max - avatar