当我 console.log 我的数组时,它显示长度为零。我使用返回 true
的 Array.isArray
检查它是一个数组。还打印出数组值以确保它们存在并显示在控制台中:
[]
0: "a"
1: "b"
2: "c"
3: "d"
length: 4
__proto__: Array(0)
我看到 __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
我主要是尝试在此代码之后添加一个 for 循环,以读取每个值并将其用于其他用途。但是我无法遍历数组,因为它注册为空。
最佳答案
对于其他面临类似问题的人:
您很可能在异步函数中填充数组。
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
关于javascript - 数组/列表长度为零但数组不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48120547/