JavaScript 字符串转int数组
var result ="1fg";
for(i =0; i < result.length; i++){
var chr = result.charAt(i);
var hexval = chr.charCodeAt(chr)
document.write(hexval + " ");
}
这给出了 NaN 102 103。
可能是因为它将“1”视为整数或类似的东西。有什么方法可以转换 “1”->字符串到正确的整数?在本例中:49。
所以它将是
49 102 103 而不是 NaN 102 103
干杯,
蒂莫
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
charCodeAt
函数采用索引,而不是字符串。当你向它传递一个字符串时,它会尝试将字符串转换为数字,如果不能,则使用
0
。您的第一次迭代调用
'1'.charCodeAt('1')
。它将把'1'
解析为数字,并尝试获取字符串中的第二个字符代码。由于该字符串只有一个字符,即NaN
。您的第二次迭代调用
'f'.charCodeAt('f')
。由于'f'
无法解析为数字,因此它将被解释为0
,这将为您提供第一个字符代码。您应该编写
var hexval = result.charCodeAt(i)
来获取原始字符串中给定位置的字符代码。您还可以编写
var hexval = chr.charCodeAt(0)
来获取chr
字符串中单个字符的字符代码。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'sNaN
.Your second iteration calls
'f'.charCodeAt('f')
. Since'f'
cannot be parsed as a number, it will be interpreted as0
, 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 thechr
string.