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

问题描述 投票:0回答:1

我的代码的产生错误的部分是我弄清楚了为什么僵尸程序无法通过将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');
javascript node.js discord.js
1个回答
0
投票

[constletif等语句之后,如果没有块(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)

© www.soinside.com 2019 - 2024. All rights reserved.