I have a Tampermonkey script that adds some information to a browser-based game. I use a simple piece of code to add thousand separators to numbers based on the players' locales:
function nThousand(x) {
return x.toLocaleString();
}
This function is used in a lot of the code, for example:
$("#CustomStats" + stat).html(
"<b>" + texts[lang].stat_points_need + ":</b> " + nThousand(remainingPoints) + "<br />" +
"<b>" + texts[lang].money_need + ": </b>" + nThousand(remainingMoney) + "<br />" +
"<b>" + texts[lang].money_spent + ": </b>" + nThousand(currentMoney) + "<br /><br />" +
"<b>" + texts[lang].bought_points + ": </b>" + nThousand(boughtPoints) + "<br />" +
"<b>" + texts[lang].equipment_points + ": </b>" + nThousand(itemPoints) + "<br />" +
"<b>" + texts[lang].points_from_level + ": </b>" + nThousand(skillPoints) + "<br />"
);
This has worked perfectly for ages, but for some reason on one particular platform the game runs on, the script now refuses to load and gives the following error message:
Cannot read property 'toLocaleString' of undefined
I've gone back several dozen versions to make sure it wasn't something I added or changed recently, and I honestly don't even know where I would start solving this issue. The function only runs when there is a value to be localised and it's only on one specific platform the game runs on that it does this.
My question: what could be causing this and how would I go about solving this problem?
The problem isn't with toLocaleString
, the issue is that somewhere you're passing undefined
to your function. You'll need to figure out why that's happening through debugging. It could also be a good idea to add a guard to your function that returns an empty string if it's passed a non-string value.