+ 2

i dont understand this

var myArr = [] myArr[0] = 10; myArr[1] = 20; myArr.foo = 30; console.log(myArr.length); answer: 2 why answer is 2? what is foo?

14th Sep 2018, 7:01 PM
Deaf Guy Bad English
Deaf Guy Bad English - avatar
2 Respostas
+ 3
Unlike other programming languages, JavaScript does not support arrays with named indexes (a.k.a. associative arrays/hashes) and always use numbered indexes. JavaScript redefines the named indexes ("myArr.foo" in your example) to a standard object, and therefore "myArr.length" only accounts for the numbered indexes (myArr[0] & myArr[1] in your example) and returns the array length as 2.
14th Sep 2018, 7:50 PM
Alex
0
foo is just a placeholder.
15th Sep 2018, 10:18 PM
Arda Aydın
Arda Aydın - avatar