开发者

Javascript string to int array

var result ="1fg";
for(i =0; i < r开发者_如何学Goesult.length; i++){
  var chr = result.charAt(i);
  var hexval = chr.charCodeAt(chr)
  document.write(hexval + " ");
}

This gives NaN 102 103.

Probably because it's treating the "1" as a integer or something like that. Is there a way I can convert the "1"->string to the correct integer? In this case: 49.

So it will be

49 102 103 instead of NaN 102 103

Cheers,

Timo


The charCodeAt function takes an index, not a string.

When you pass it a string, it will try to convert the string to a number, and use 0 if it couldn't.

Your first iteration calls '1'.charCodeAt('1'). It will parse '1' as a number and try to get the second character code in the string. Since the string only has one character, that's NaN.

Your second iteration calls 'f'.charCodeAt('f'). Since 'f' cannot be parsed as a number, it will be interpreted as 0, which will give you the first character code.


You should write var hexval = result.charCodeAt(i) to get the character code at the given position in the original string.

You can also write var hexval = chr.charCodeAt(0) to get the character code of the single character in the chr string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜