我正在尝试制作一个不和谐级别的机器人,我需要从 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:无法读取未定义的属性(读取“长度”)
在客户处。
您正在分配(单个等于)
undefined
到数据:
if(data = undefined)
^^^
如果您使用 double equals 检查,它将起作用:
if (data == undefined) { ... }
你也可以做
if (!data) { ... }
。
这是因为
if(data = undefined)
。请注意,只有一个=
标志。
因此,
data
将被指定为undefined
,并且该行将变为if(undefined)
。因此 if 块不会被执行。
只需将此行更新为
if(data == undefined)