+ 2

Javascript I need help Arrays

var arr = [1,2,3,4]; arr[arr[1]] = 5; console.log(arr) Why this code is // 1,2,5,4 Inistead of // 1,5,3,4 I need help

13th Feb 2020, 11:46 AM
Noob
Noob - avatar
4 Answers
+ 9
arr = [1,2,3,4]; | Index 0,1,2,3 arr[ 1 ] == 2 right ? So arr[ arr[1] ] == arr[ 2 ] Finally we set index 2 = 5 arr[ 2 ] = 5 We have arr = [1,2,5,4]; | Index 0,1,2,3
13th Feb 2020, 11:54 AM
Pedro H.J
Pedro H.J - avatar
+ 7
arr[1] = 2 arr[arr[1]] = arr[2] Finally: arr[2] = 5 The array starts from 0. (0 is the first element arr[0] = 1 arr[1] = 2 ... arr[3] = 4
13th Feb 2020, 11:53 AM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
+ 2
Thanks i get it its can a tricky 😂
13th Feb 2020, 11:57 AM
Noob
Noob - avatar
0
Pedro H.J 💚 Alex Tușinean 🍏 thanks guys... Had to stare at this for awhile until it all made sense lol đŸ‘đŸœ
19th Aug 2020, 8:46 PM
Zone
Zone - avatar