Riggun
Riggun

Reputation: 315

Javascript array can't acces by index

I wounder why can't I access array item by index? I've created global array just like this:

var myArr=[];

Then in a function I've used a simple loop to fill it with numbers from 1 to 10 just in test purposes. It seems it is filled because if I call

console.log(myArr);

It returns me this enter image description here

But if I try to use indexes in the same console call

console.log(myArr[2]);

It returns undefined and also myArr.length returns 0

Why??

Upvotes: 0

Views: 49

Answers (1)

zkldi
zkldi

Reputation: 94

When you click on the array in your developer tools, it shows you the current values inside the array. I assume you are inserting items into the array after calling console.log on the array.

Since you expand the array in the developer tools after it has been populated, it appears populated, but at the time of console.logging, it actually isnt (and is just an empty array).

Upvotes: 1

Related Questions