数组/列表长度为零但数组不为空

374*_*374 5 javascript arrays vue.js

当我 console.log 我的数组时,它显示长度为零。我检查它是一个使用Array.isArraywhich 返回的数组true。还打印出数组值以确保它们存在并显示在控制台中:

[]
0: "a"
1: "b"
2: "c"
3: "d"
length: 4
__proto__: Array(0)
Run Code Online (Sandbox Code Playgroud)

我看到了__proto__: Array(0),我假设这意味着它是一个长度为 0 的数组,但是如何使它的长度不为零,以便我可以遍历它?

我有一个想法是这个函数可能是异步的,但我不确定如何解决这个问题。

参考代码:

var list=[]
//getting data from a database
snapshot.forEach(function (node) {
   list.push(node.val())
   console.log(node.val()) //values print out
})
console.log(list) //array is length zero
Run Code Online (Sandbox Code Playgroud)

我基本上是尝试在此代码之后添加一个 for 循环来读取每个值并将其用于其他用途。但是我无法遍历数组,因为它注册为空。

saf*_*zik 6

对于面临类似问题的任何其他人:

您很可能在异步函数中填充数组。

function asyncFunction(list){
 setTimeout(function(){
    list.push('a');
    list.push('b');
    list.push('c');
    console.log(list.length); // array length is 3 - after two seconds
 }, 2000); // 2 seconds timeout
}

var list=[];
//getting data from a database
asyncFunction(list);
console.log(list.length) //array is length zero - after immediately
console.log(list) // console will show all values if you expand "[]" after two seconds
Run Code Online (Sandbox Code Playgroud)


Dyl*_*ght 0

我需要查看您的更多代码,但这正是您想要的。

var arr = [1, 3, 5, 6];
console.log(arr.length);
for (var i = 0; i < arr.length; i++){
  console.log(arr[i]);
}
Run Code Online (Sandbox Code Playgroud)