2017-04-01 44 views
0

我在這裏得到了一些非常奇怪的結果。我試圖將一個字符串轉換爲一個整數。考慮下面的代碼。嘗試將字符串轉換爲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

回答

1

您對您的 「詮釋」 價值單一quotationmarks。

將數據返回到聊天「5」

看起來像是你的插座傳輸之前逃脫?

+0

你是對的!它已經逃脫了......趕上!當我被允許時,我會在2分鐘內給你答覆。謝謝! – Tony

+0

不客氣。未來:如果它說是NaN,那就是NaN;) – Ben

-3

嘗試使用parseInt()

var num = '5'; 
 

 
alert(parseInt(num));

+1

如果您閱讀我的整篇文章,您會看到我已經嘗試過。它甚至粗體。 – Tony

+0

你確定chatid的值總是一個數字串嗎? – four

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