TypeError:无法读取nodejs中未定义的属性(阅读“长度”)

tnkciper  于 9个月前  发布在  Node.js
关注(0)|答案(2)|浏览(130)

我试图制作一个不和谐级别的机器人,我需要从JSON文件中抓取一些ingo并比较长度,但我在if语句中得到了标题中的错误:

if(message.author.bot == false && userinput != '!level')
    {   let data = JSON.parse(fs.readFileSync("./level.json", "utf-8"));
        // console.log(data);
        if(data === undefined)
        {
            console.log("data is undefined");
            return;
            //if date is undefined (failsafe method)
        }
        // for loop looping through array, if we are going to find user, we add +1 experience and exit the loop
        if( data.length > 0){
        for(let i=0;i< data.length; i++)
        if(message.author.id == data[i].userID)
        {
            data[i].exp++;
            fs.writeFileSync("./level.json", JSON.stringify(data));
            i = data.length;
        }
            
        }
        //if file is empty, add user details to file, only run once
        else
        if(data.length <= 0)
        {
        const newuser = {
                    "userID" : message.author.id,
                    "exp" : 1
                }
                data = [newuser];
                fs.writeFileSync("./level.json", JSON.stringify(data));
        }
        
        //is going to add experience to user
        
    }

字符串
错误日志:

if( data.length > 0){
             ^


TypeError:无法在客户端读取未定义的属性(阅读“length”)。

xmakbtuz

xmakbtuz1#

您正在 * 将 *(单个等于)undefined分配给数据:

if(data = undefined)
        ^^^

字符串
如果你检查 double equals,它会工作:

if (data == undefined) { ... }


你也可以做if (!data) { ... }

fcg9iug3

fcg9iug32#

这是因为if(data = undefined)。请注意,只有一个=符号。
因此,data将被分配为undefined,这一行将成为if(undefined)。因此,if块将不会被执行。
只需将此行更新为if(data == undefined)

相关问题