尝试将字符串转换为int时获得NaN
问题描述:
我在这里得到了一些非常奇怪的结果。我试图将一个字符串转换为一个整数。考虑下面的代码。尝试将字符串转换为int时获得NaN
//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
请注意,我已经试过号()和parseInt函数()
然而,试图在的jsfiddle代码,它工作正常。我不知道我为什么得到NaN。有任何想法吗?
var num = '5';
alert(Number(num));
答
可以使用+来快速转换为数字,并提供备用
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));
尝试输出'msg.chatid.length'和'msg.chatid.charCodeAt(0)' – 4castle
我有一种感觉,chatid的实际内容是'5'而不是'5',这就是为什么它不能被分析成数字。否则,我看不出为什么你会在你的console.log中得到这些引号。 *编辑*:用下一条评论确认它,char代码是'''是39. – JCOC611
@ 4castle'msg.chatid.length'返回3和'msg.chatid.charCodeAt(0)'返回39 – Tony