Reputation: 4541
The answer may be obvious but I don't see
I have a JavaScript object virtualTable. I write :
parseInt(virtualTable["resource_" + resourceId])
it returns NaN
I check virtualTable["resource_" + resourceId]
with an alert and the answer is "690"
If I alert parseInt("690")
it works fine and returns 690
What is wrong then?
the whole code :
if(!virtualTable.hasOwnProperty("resource_" + resourceId)) {
virtualTable["resource_" + resourceId] = "\"" + minutesToFill + "\"";
}
var timeForTarget = (target.end.getTime() - target.start.getTime()) / 60000;
var timeInVirtualTable;
var tooltipInTarget
if(virtualTable["resource_" + resourceId].indexOf("_") == -1) {
timeInVirtualTable = parseInt(virtualTable["resource_" + resourceId]);
tooltipInTarget = "";
} else {
timeInVirtualTable = parseInt(virtualTable["resource_" + resourceId].substring(0, virtualTable["resource_" + resourceId].indexOf("_")));
tooltipInTarget = virtualTable["resource_" + resourceId].substring(virtualTable["resource_" + resourceId].indexOf("_"));
}
Upvotes: 0
Views: 193
Reputation: 38416
Per your statement,
I check virtualTable["resource_" + resourceId] with an alert and the answer is "690"
I'm assuming that the value inside virtualTable["resource_" + resourceId]
is literally "690"
, including the quotes. Because of this, it's NaN
, or, not-a-number (due to the leading double-quote).
If this will be common input, you can strip the double-quotes from your value before (or during) the call to parseInt using replace()
:
var value = virtualTable["resource_" + resourceId].replace(/"/g, '');
var number = parseInt(value);
or:
var number = parseInt(virtualTable["resource_" + resourceId].replace(/"/g, ''));
EDIT (parseInt()
's base):
Building on a comment, you should also remember to always specify the numeric-base to parse the input to. In your case, you want base-10 (or "decimal"). This is specified as the second parameter to parseInt()
:
var number = parseInt(value, 10);
or
var number = parseInt(virtualTable["resource_" + resourceId].replace(/"/g, ''), 10);
Upvotes: 7