获取 SyntaxError:词法声明不能出现在单语句上下文中

For*_*ods 0 javascript node.js discord.js

我的代码的 let 部分产生了一个错误我想出了为什么机器人不会通过将 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(`https://openweathermap.org/data/2.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');
Run Code Online (Sandbox Code Playgroud)

che*_*som 5

不能使用词汇的声明(const以及let类似的语句之后)ifelsefor等不带有块({})。改用这个:

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
});
Run Code Online (Sandbox Code Playgroud)

编辑第二个问题

您需要检查消息是否由机器人发送,以便它忽略它们发送的所有消息,包括“无效邮政编码”消息:

client.on("message", (message) => {
    if (!message.author.bot) return;
    // rest of code
});
Run Code Online (Sandbox Code Playgroud)

否则,“无效邮政编码”消息将触发机器人发送另一条“无效邮政编码”消息,因为“无效邮政编码”显然不是有效的邮政编码。


此外,更改parseInt(zipCode) === NaNNumber.isNaN(parseInt(zipCode)). NaN === NaNfalse由于某种原因在JS,所以你需要使用Number.isNaN。您也可以这样做,isNaN(zipCode)因为将isNaN其输入强制为一个数字,然后检查它是否为NaN.

console.log(`0 === NaN: ${0 === NaN}`)
console.log(`'abc' === NaN: ${'abc' === NaN}`)
console.log(`NaN === NaN: ${NaN === NaN}`)
console.log('')
console.log(`isNaN(0): ${isNaN(0)}`)
console.log(`isNaN('abc'): ${isNaN('abc')}`)
console.log(`isNaN(NaN): ${isNaN(NaN)}`)
console.log('')
console.log(`Number.isNaN(0): ${Number.isNaN(0)}`)
console.log(`Number.isNaN('abc'): ${Number.isNaN('abc')}`)
console.log(`Number.isNaN(NaN): ${Number.isNaN(NaN)}`)
Run Code Online (Sandbox Code Playgroud)


编辑 2

试试这个代码:

client.on("message", (message) => {
  if (message.content.includes("_weather") && !message.author.bot) {
    let zipCode = message.content.split(" ")[1];
    if (zipCode === undefined || zipCode.length != 5 || Number.isNaN(parseInt(zipCode))) {
      message.channel.send("`Invalid Zip Code. Please follow the format: _weather <#####>`")
        .catch(console.error);
      return;
    } else {
      fetch(`https://openweathermap.org/data/2.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
        `);

          }
        });
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

编辑 3

if (message.content.startsWith("_weather") && !message.author.bot)
Run Code Online (Sandbox Code Playgroud)