简体   繁体   中英

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 .

The array isn't empty and when I console.log() it I've gotten.

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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