简体   繁体   中英

Javascript string to int array

var result ="1fg";
for(i =0; i < result.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM