【发布时间】:2017-04-01 00:17:47
【问题描述】:
我在这里得到了一些非常奇怪的结果。我正在尝试将字符串转换为整数。考虑下面的代码。
//Send back to client.
io.emit('returned message', {
'message': message,
'chatid': chatid,
'userid': userid
});
console.log("Returning the data to chat " + chatid);
将数据发送回客户端,控制台日志如下所示:
将数据返回到聊天'5'
在我的客户端中
alert(typeof msg.chatid);
alert(msg.chatid)
var test = Number(msg.chatid);
alert(typeof test)
alert(test);
产生以下结果
字符串和'5' 数字和NaN
请注意我已经尝试过 Number() 和 parseInt()
但是,尝试在 Jsfiddle 中编写代码,它工作正常。我不知道为什么我会得到 NaN。有什么想法吗?
var num = '5';
alert(Number(num));
【问题讨论】:
-
尝试输出
msg.chatid.length和msg.chatid.charCodeAt(0) -
我感觉chatid的实际内容是
'5'而不是5,这就是为什么它不能被解析成数字的原因。否则,我看不出你为什么会在你的 console.log 上得到这些引号。 编辑:用下一条评论确认,'的字符码是39。 -
@4castle
msg.chatid.length返回 3 和msg.chatid.charCodeAt(0)返回 39 -
@RokoC.Buljan 我正在使用 Socket.io 将数据从服务器发送到客户端。我在客户端和服务器上都使用了 console.log,两个结果都返回 '5'
标签: javascript jquery