这段代码导致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°C,风速为-6°C。来自ESE的风速为15-25公里/小时。
部分多云。低至3°C。来自ESE的风速为40-45公里/小时。
答案 0 :(得分:3)
您需要了解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
是很多更简洁,更容易阅读。
另请注意,我在switch
示例中将值放在引号中。如果你要将字符串与字符串进行比较,你需要确保你真的这样做。表达式'5' == 5
会将这两个值视为相等(即使它们不相等),switch
也不会。 ==
的原因是它是松散的相等运算符。它使用abstract equality comparison algorithm,有效地(在这种情况下)将表达式转换为Number('5') == 5
(不 '5' == String(5)
)。 ==
运算符愉快地比较不同类型的值,执行一系列检查和转换以得出要比较的内容(请参阅上面的链接)。 switch
不这样做。对于与您正在测试的表达式匹配的交换机的case
子句之一,值必须属于同一类型 - 交换机永远不会将'5'
和5
视为匹配。 switch
使用===
(严格相等)运算符,而不是==
(松散相等)运算符。
请注意,我使用的是temp.charAt(0)
,而不仅仅是temp.substr(0)
(感谢Felix,我甚至没有看过它)。 temp.substr(0)
只是复制整个字符串。您可以使用temp.substr(0, 1)
或temp.charAt(0)
。