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

标签 javascript arrays vue.js

当我 console.log 我的数组时,它显示长度为零。我使用返回 trueArray.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/

相关文章:

vue.js - vue - 插值 html 值

javascript - 在 Vue.js 中路由器链接的 ":to"属性中传递 props

javascript - 选择和选项标签的 HTML 和 CSS 问题

javascript - for 循环中出现意外值

arrays - 为什么 Go slice 不能像数组用作键一样用作 Go 映射中的键?

javascript - 选中所有复选框,不将名称插入数组

css - 如何获取 CSS 溢出和高度 :calc to work in a resizable div

Javascript 函数式编程测验

javascript - 如何使用 JavaScript 替换文章中的随机匹配文本?

javascript - 用 arrayBuffer 录制 mp3