数组/列表长度为零,但数组不为空 [英] Array/List length is zero but Array is not empty

查看:81
本文介绍了数组/列表长度为零,但数组不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  []0:"a"1:"b"2:"c"3:"d"长度:4__proto__:数组(0) 

我看到了 __ proto__:Array(0),我假设这是一个长度为0的数组,但是如何使它成为非零长度以便可以迭代它呢?/p>

我曾经想过,这个函数可能是异步的,但是我不确定如何解决这个问题.

参考代码:

  var list = []//从数据库获取数据snapshot.forEach(函数(节点){list.push(node.val())console.log(node.val())//值打印出来})console.log(list)//数组长度为零 

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

解决方案

面向其他面临类似问题的人:

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

  function asyncFunction(list){setTimeout(function(){list.push('a');list.push('b');list.push('c');console.log(list.length);//数组长度为3-两秒钟后},2000年);//2秒超时}var list = [];//从数据库获取数据asyncFunction(list);console.log(list.length)//数组的长度为零-立即之后console.log(list)//如果两秒钟后展开"[]",控制台将显示所有值 

When I console.log my array it shows that the length is zero. I checked that it was an array using Array.isArray which returned true. Also printed out the array values to make sure they exist and it shows in the console:

[]
0: "a"
1: "b"
2: "c"
3: "d"
length: 4
__proto__: Array(0)

I see that __proto__: Array(0) and I'm assuming this means it's a 0 length Array but how do I make it non-zero length so that I can iterate through it?

A thought I had is that this function might be asynchronous but I'm not really sure how to work around that.

Code for reference:

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

I'm basically trying to add a for loop after this code to read through each value and use it for something else. However I can't iterate through the array because it registers as empty.

解决方案

For anyone else who is facing similar issue:

You are very likely populating the array within an asynchronous function.

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

这篇关于数组/列表长度为零,但数组不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆