This piece of code causes Chrome to crash:
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);
}
Is there a more effective way to see if the first character of a string is an integer or a negative sign and if it isn’t to delete that character from the string?
Here are two types of strings that get parsed through this.
Clear. Fog overnight. Low of -2°C with a windchill of -6°C. Winds from the ESE at 15-25 km/h.
Partly cloudy. Low of 3°C. Winds from the ESE at 40-45 km/h.
You need to read up on how JavaScript (and most other languages’)
==/!=and||operators work. This line:…does not check to see if
temp.substr(0)is one of the values given. It checks iftemp.substr(0) != 0, or (separately) it checks the value1(which is always true), etc. So that condition will always be true.Since you’re doing string/character stuff, the easiest thing would probably be to use
indexOf:…or a regular expression.
The general case for that sort of “is this value any of the following” is a
switchstatement:…but again, as you’re doing string stuff,
indexOfis a lot more concise and easier to read.Also note that I’ve put the values in quotes in the
switchexample. If you’re comparing strings to strings, you want to be sure that you really do that. The expression'5' == 5will consider those two values equal (even though they’re not), theswitchwon’t. The reason==does is that it’s the loose equality operator. It uses the abstract equality comparison algorithm, which effectively (in this case) turns the expression intoNumber('5') == 5(not'5' == String(5)). The==operator happily compares values of different types, performing a series of checks and conversions to come up with something to compare (see the link above).switchdoesn’t do that. For one of thecaseclauses of a switch to match the expression you’re testing, the values must be of the same type — a switch will never consider'5'and5to match.switchuses the===(strict equality) operator, not the==(loose equality) operator.Note that I’ve used
temp.charAt(0)rather than justtemp.substr(0)(thanks Felix, I wasn’t even looking at that).temp.substr(0)just makes a copy of the whole string. You could usetemp.substr(0, 1)ortemp.charAt(0).