简体   繁体   English

Javascript 数组无法按索引访问

[英]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.然后在一个函数中,为了测试目的,我使用了一个简单的循环来填充从 1 到 10 的数字。 It seems it is filled because if I call似乎已经满了 因为如果我打电话

console.log(myArr);

It returns me this它返回给我这个在此处输入图片说明

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它返回 undefined 并且 myArr.length 返回 0

Why??为什么??

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.我假设您在数组上调用 console.log 后将项目插入到数组中。

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).由于您在填充后在开发人员工具中展开数组,它看起来已填充,但在 console.logging 时,它实际上不是(并且只是一个空数组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM