检查第一个字符是否为int的错误,如果不是'不要删除那个字符

bug with checking if first character is int, if it isn't delete that character

本文关键字:字符 删除 如果不 是否 第一个 int 错误 检查      更新时间:2023-09-26

这段代码导致Chrome崩溃:

function forecastTemp(forecast) {
    var end = forecast.indexOf('&'),
        fcWeather = forecast.substring(0, end).length - 3,
        temp = forecast.substring(fcWeather, end);
    if (temp.substr(0) != 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 || '-') {
        do {
            fcWeather = fcWeather + 1;
            temp = forecast.substring(fcWeather, end);
        }
        while (temp.substr(0) != 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 || '-');
    }
    console.log('fcWeather: ' + fcWeather + '');
    console.log('end: ' + end + '');
    console.log('temp: ' + temp + '');
    return (temp);
}

有没有更有效的方法可以查看字符串的第一个字符是整数还是负号,以及是否不从字符串中删除该字符?

这里有两种类型的字符串可以通过此进行解析。

清除。雾连夜。-2°的下限;具有-6°C.来自ESE的风速为15-25公里/小时。

部分多云。低3°C.来自ESE的风速为40-45公里/小时。

您需要了解JavaScript(以及大多数其他语言的)==/!=||运算符的工作原理。此行:

if (temp.substr(0) != 0 || 1 || 2 || 3 || 4 || 5 || 6 || 7 || 8 || 9 || '-') {

是否检查temp.substr(0)是否为给定值之一。它检查是否为temp.substr(0) != 0,或者(单独)检查值1(始终为真)等。因此,该条件将始终为真。

既然你在做字符串/字符的事情,最简单的事情可能是使用indexOf:

if ("0123456789-".indexOf(temp.charAt(0)) >= 0) {
    // The character matches one of the ones in the string
}
else {
    // It doesn't
}

或正则表达式。

这类"此值是否为以下任意值"的一般情况是switch语句:

switch (temp.charAt(0)) {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '-':
        // It matches one of the above
        break;
    default:
        // It doesn't
        break;
}

但是,当你在做字符串的时候,indexOf是一个lot,更简洁,更容易阅读。

还要注意,在switch示例中,我已将这些值用引号括起来。如果你在比较字符串和字符串,你需要确保你真的做到了。表达式'5' == 5会认为这两个值相等(即使它们不相等),而switch不会。==这样做的原因是它是松散的相等运算符。它使用抽象等式比较算法,该算法有效地(在这种情况下)将表达式转换为Number('5') == 5而不是'5' == String(5))。==运算符很乐意比较不同类型的值,执行一系列检查和转换以得出要比较的内容(请参阅上面的链接)。switch不这么做。要使开关的case子句之一与正在测试的表达式匹配,这些值必须是相同类型—交换机将永远不会考虑CCD_ 19和CCD_。switch使用===(严格相等)运算符,而不是==(松散相等)运算符。


请注意,我使用了temp.charAt(0),而不仅仅是temp.substr(0)(谢谢Felix,我甚至没有看)。temp.substr(0)只是复制了整个字符串。您可以使用temp.substr(0, 1)temp.charAt(0)