TypeError: Cannot read properties of undefined (reading 'length') in nodejs
TypeError: Cannot read properties of undefined (reading 'length') in nodejs
我正在尝试制作一个不和谐级别的机器人,我需要从 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')
在客户端。<匿名>
您正在分配(单等号)undefined
给数据:
if(data = undefined)
^^^
如果你检查 double equals,它会起作用:
if (data == undefined) { ... }
你也可以if (!data) { ... }
.
这是因为if(data = undefined)
。请注意,只有一个 =
符号。
因此,data
将被分配为 undefined
,此行将变为 if(undefined)
。因此 if 块将不会被执行。
只需将此行更新为 if(data == undefined)
我正在尝试制作一个不和谐级别的机器人,我需要从 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') 在客户端。<匿名>
您正在分配(单等号)undefined
给数据:
if(data = undefined)
^^^
如果你检查 double equals,它会起作用:
if (data == undefined) { ... }
你也可以if (!data) { ... }
.
这是因为if(data = undefined)
。请注意,只有一个 =
符号。
因此,data
将被分配为 undefined
,此行将变为 if(undefined)
。因此 if 块将不会被执行。
只需将此行更新为 if(data == undefined)