词法声明不能出现在单语句上下文中"/>
Getting SyntaxError:词法声明不能出现在单语句上下文中
我的代码的产生错误的部分是我弄清楚了为什么僵尸程序无法通过将client.login移到最下面来启动新错误,其中包括它只会发送“无效的邮政编码。请遵循以下格式:_weather ”,即使您输入了邮政编码
client.on("message", (message) => {
if (message.content.includes("_weather") && message.author.bot === false)
let zipCode = message.content.split(" ")[1];
if (zipCode === undefined || zipCode.length != 5 || parseInt(zipCode) === NaN) {
message.channel.send("`Invalid Zip Code. Please follow the format: _weather <#####>`")
.catch(console.error);
return;
} else {
fetch(`.5/weather?zip=${zipCode},us&appid=439d4b804bc8187953eb36d2a8c26a02`)
.then(response => {
return response.json();
})
.then(parsedWeather => {
if (parsedWeather.cod === '404') {
message.channel.send("`This zip code does not exist or there is no information avaliable.`");
} else {
message.channel.send(`
The Current Weather
Location: ${parsedWeather.name}, ${parsedWeather.sys.country}
Forecast: ${parsedWeather.weather[0].main}
Current Temperature: ${(Math.round(((parsedWeather.main.temp - 273.15) * 9 / 5 + 32)))}° F
High Temperature: ${(Math.round(((parsedWeather.main.temp_max - 273.15) * 9 / 5 + 32)))}° F
Low Temperature: ${(Math.round(((parsedWeather.main.temp_min - 273.15) * 9 / 5 + 32)))}° F
`);
}
});
}
});
client.login('token');
回答如下:[const
,let
,if
等语句之后,如果没有块(else
),则不能使用词法声明(for
和{}
)。改用它:
client.on("message", (message) => {
// declares the zipCode up here first
let zipCode
if (message.content.includes("_weather") && message.author.bot === false)
zipCode = message.content.split(" ")[1];
// rest of code
});
编辑第二个问题
您需要检查消息是否是由漫游器发送的,以便它会忽略它们发送的所有消息,包括“无效的邮政编码”消息:
client.on("message", (message) => {
if (message.author.bot) return;
// rest of code
});
[否则,“无效邮政编码”消息将触发机器人发送另一条“无效邮政编码”消息,因为“无效邮政编码”显然不是有效的邮政编码。
也将parseInt(zipCode) === NaN
更改为Number.isNaN(parseInt(zipCode))
。由于JS中的NaN === NaN
出于某种原因,因此您需要使用false
。您也可以只执行Number.isNaN
,因为Number.isNaN
将其输入强制为数字,然后检查其是否为isNaN(zipCode)
。
isNaN
更多推荐
Getting SyntaxError:词法声明不能出现在单语句上下文中
发布评论