【问题标题】:getting NaN when trying to cast string to int尝试将字符串强制转换为 int 时得到 NaN
【发布时间】: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.lengthmsg.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


【解决方案1】:

“int”值周围有单引号。

将数据返回到聊天'5'

看起来它在你的套接字传输之前就被转义了?

【讨论】:

  • 你是对的!它已经逃脱了……好捕获!如果允许,我会在 2 分钟内回复您。谢谢!
  • 不客气。并且在未来:如果它说它是 NaN,它就是 NaN ;)
【解决方案2】:

您可以使用 + 快速转换为数字并提供回退

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

【讨论】:

    【解决方案3】:

    尝试使用parseInt()

    var num = '5';
    
    alert(parseInt(num));

    【讨论】:

    • 如果您阅读我的整个帖子,您会发现我已经尝试过了。它甚至加粗。
    • 你确定chatid的值总是一个数字字符串吗?
    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 2020-01-21
    • 1970-01-01
    • 2016-10-27
    • 2018-07-06
    • 2012-05-26
    • 1970-01-01
    • 2014-12-22
    相关资源
    最近更新 更多