简体   繁体   English

数组长度为零但数组不为空

[英]Array length is zero but Array is not empty

When I'm trying to iterate through an array, get it's length or access indexes I'm getting Error TypeError: Cannot read property 'map' of undefined .当我试图遍历一个数组,获取它的长度或访问索引时,我收到 Error TypeError: Cannot read property 'map' of undefined

The array isn't empty and when I console.log() it I've gotten.数组不是空的,当我使用console.log() ,我得到了它。

0: {user_id: 11, …}
length: 1
__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?我看到proto : Array(0) 并且我假设这意味着它是一个长度为 0 的数组,但是我如何使它的长度不为零以便我可以遍历它?

Code for reference:参考代码:

useEffect(() => {
     blog.authors.map(data => {
         console.log(data)
      })
}, [blog])

I've also tried.我也试过了。 It worked, but I immediately got the similar error.它有效,但我立即收到了类似的错误。

useEffect(() => {
        (async() => {
            await blog.authors.map(data => {
                console.log(data)
            })
        })()
}, [blog])

简单检查blog.authors是否未定义解决了它。

No, array indexes are 0 based .不,数组索引是0 based

var arr = ['a', 'b'];
console.log(arr.length); // => 2
console.log(arr[0]);     // => a

So instead of making confusing assertion about what works and not without providing the code them providing other code, could you just see the result of that:因此,与其对有效的方法做出令人困惑的断言,而不是在不提供代码的情况下提供其他代码,您能否只看到结果:

useEffect(() => {
     console.log({blog});
     console.log({authors: blog.authors });
     blog.authors.map(data => {
         console.log(data)
      })
}, [blog])

Because I suspect that blog changed overtime, having some authors and something authors undefined.因为我怀疑blog随着时间的推移而改变,有一些作者和一些作者未定义。

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

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