尝试将字符串转换为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));

+0

尝试输出'msg.chatid.length'和'msg.chatid.charCodeAt(0)' – 4castle

+1

我有一种感觉,chatid的实际内容是'5'而不是'5',这就是为什么它不能被分析成数字。否则,我看不出为什么你会在你的console.log中得到这些引号。 *编辑*:用下一条评论确认它,char代码是'''是39. – JCOC611

+1

@ 4castle'msg.chatid.length'返回3和'msg.chatid.charCodeAt(0)'返回39 – Tony

您对您的 “诠释” 价值单一quotationmarks。

将数据返回到聊天“5”

看起来像是你的插座传输之前逃脱?

+0

你是对的!它已经逃脱了......赶上!当我被允许时,我会在2分钟内给你答复。谢谢! – Tony

+0

不客气。未来:如果它说是NaN,那就是NaN;) – Ben

尝试使用parseInt()

var num = '5'; 
 

 
alert(parseInt(num));

+1

如果您阅读我的整篇文章,您会看到我已经尝试过。它甚至粗体。 – Tony

+0

你确定chatid的值总是一个数字串吗? – four

可以使用+来快速转换为数字,并提供备用

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));