Javascript arithmetic fun
Posted: Sat Oct 24, 2009 11:11 am
Javascript doesn't know types - variables are whatever type makes sense at the time.
eg:
The reason k contains "11" instead of 2 is that j is a string and Javascript ends up using string concatenation rather than arithmetic to compute the value for k.
To work around this, always use parseInt() when working with variables whose type you're not 100% sure of:
This was the underlying reason for an odd bug whereby scooping sometimes filled my cargohold from a single barrel. The culprit was the new player.ship.manifest object and the way cargo is awarded using it.
eg:
In this case though, the quantity was first retrieved from somewhere else, then printed as a string, before being awarded. Printing the quantity as a string converted it to a string type and then stuffed up the next calculation.
The fix is to either award the cargo before performing the string operation, or to make really sure, wrap quantity in parseInt:
eg:
Code: Select all
var i = 1; // Number
var j = "1"; // String
var k = i + j; // "11" -> probably what wasn't expected.
To work around this, always use parseInt() when working with variables whose type you're not 100% sure of:
Code: Select all
var k = parseInt(i) + parseInt(j); // 2 -> probably what was expected.
This was the underlying reason for an odd bug whereby scooping sometimes filled my cargohold from a single barrel. The culprit was the new player.ship.manifest object and the way cargo is awarded using it.
eg:
Code: Select all
player.ship.manifest["food"] += 1; // Award 1 ton of Food
Code: Select all
var quantity = <something>;
player.consoleMessage(quantity + "<some string>");
player.ship.manifest["food"] += quantity; // WARNING
Code: Select all
player.ship.manifest["food"] += parseInt(quantity); // Ok