我在这里得到了一些非常奇怪的结果。我试图将字符串转换为整数。请考虑以下代码。
//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));

答案 0 :(得分:1)
你的" int"周围有单引号值。
将数据退回聊天' 5'
看起来它在你的套接字传输之前被转义了吗?
答案 1 :(得分:0)
您可以使用+快速转换为数字并提供后备
var getNum = (n) => (+n) ? +n : -1
var chatid = '5'
var chatidinvalid = '5test'
var chatidnan = NaN
console.log("Returning the data to chat ", getNum(chatid));
console.log("Returning the data to chatidinvalid: ", getNum(chatidinvalid));
console.log("Returning the data to chatidinvalid: ", getNum(chatidnan));

答案 2 :(得分:-4)
尝试使用parseInt()
。
var num = '5';
alert(parseInt(num));