Reputation: 9
I am aware of name.charCodeAt(0)
. I am having issued with the following code, so I want a solution for below.
var number= 2;
var t = number.charCodeAt(0);
console.log(t);
The answer needs to be in ASCII. I am getting the log as 2 and not as ASCII value 50. What can be the issue?
Upvotes: 0
Views: 2469
Reputation: 246
Just convert the number to String and call the method on it.
var number = 2;
var numberInString = number.toString();
var code = numberInString.charCodeAt(0);
console.log(code);
Upvotes: 1
Reputation: 32066
You have to cast a number to a string first to use .charCodeAt
to get the numerical character code.
var number = 2;
var t = String( number ).charCodeAt( 0 );
console.log( t ); // 50
Upvotes: 1
Reputation: 66324
ASCII is a way of representing String data. You need to first convert your Number to String;
Remember also that String can have arbitrary length so you'll need to iterate over every character.
var x = 2,
str_x = '' + x,
chrs = Array.prototype.map.call(str_x, function (e) {return e.charCodeAt(0);});
chrs; // [50]
Finally, JavaScript works with UTF-16/UCS-2 and not plain ASCII. Luckily the values for digits are the same in both so you don't have to do any further transformation here.
Upvotes: 3