Reputation: 1275
I'm trying to take a character and increment or decrement it. I'm attempting to use String.fromCharCode
to accomplish this. While the following works in a console
'Na' + String.fromCharCode(78 + n) // n is 2 in this example, can even hard-code it
seems to work properly and gives me NaP
, something else in my code is giving me Na̎
instead.
Here's the code block that is being executed
if (ifTypes(a, b, 'integer', 'NaN')) { // disregard this, inside code IS executing
console.log("a: " + JSON.stringify(a) + " b: " + JSON.stringify(b));
var n = a[1] === 'NaN' ? b[0] : a[0];
var output = 'Na' + String.fromCharCode(78 + n);
console.log("output: " + output);
return output;
}
From the console for verification:
a: [null,"NaN"] b: ["2","integer"]
output: Na̎ // <-- SO's code highlighter is messing that up
And yes, if anyone recognizes what I'm doing, I am implementing the interpreter from xkcd's 1537. If you want to see this code in action and maybe try to read through my console output, I've got it online here. Just click in the lighter bar and press enter, it's just simulating a terminal.
I suspect the problem is some strange ascii/unicode toggle. I've tried putting the 'Na'
inside the String.fromCharCode
but it gives the similar results. Though a
should be [NaN, "NaN"]
, I don't think that's the issue. I do need to track down that bug too.
Upvotes: 0
Views: 55
Reputation: 10557
n
is a string, not an integer, so the addition isn't doing what you expect.
Change
var output = 'Na' + String.fromCharCode(78 + n);
to
var output = 'Na' + String.fromCharCode(78 + parseInt(n));
Upvotes: 1
Reputation: 1578
I think the problem is that you're adding "2"
and 78
, instead of 2
and 78
.
function print(s) {
document.querySelector("#result").innerHTML += "<pre>" + s + "</pre>";
}
var a = [null, "NaN"];
var b = ["2", "integer"];
var n = a[1] === 'NaN' ? b[0] : a[0];
var output = 'Na' + String.fromCharCode(78 + n);
print("output 1: " + output);
output = 'Na' + String.fromCharCode(78 + (typeof n == "number" ? n : parseInt(n, 10)));
print("output 2: " + output);
<div id="result"></div>
Upvotes: 2