Chrome:parseInt()返回NaN [英] Chrome: parseInt() returns NaN

查看:117
本文介绍了Chrome:parseInt()返回NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个只返回数字的AJAX调用:

I did an AJAX call which just returns a number:

var lastID = 0;
var loading = true;

// Get latest message ID
$.ajax({
    url: "libs/getLatestMessageID.ajax.php",
    dataType: "text",
    type: "GET",
    success: function(data) {
        lastID = data;
        console.log("Received latest message ID: " + typeof(data) + " \"" + data + "\" " + parseInt(data, 10));
    },
});

我从服务器收到的是一个字符串,例如21,现在需要转换为数字,以便JS可以用它来计算。在Firefox中,它工作正常,console.log()行的输出是:

What I receive from the server is a string, e.g. "21", which now needs to be converted to a number so JS can calculate with it. In Firefox, it works fine, the output of the console.log() row is:


收到最新的消息ID:string 2121

Received latest message ID: string "21" 21

但谷歌浏览器让parseInt()返回:

But Google Chrome makes parseInt() return this:


收到最新消息ID:string21NaN

Received latest message ID: string "21" NaN

这里出了什么问题?

推荐答案

该字符串以不可打印的无效字符作为前缀,导致 parseInt()无法将字符串解析为数字,因此返回 NaN (非数字)。

The string is prefixed with non-printable invalid chars which causes the parseInt() to not be able to parse the string as number and therefor returns NaN (Not-a-Number).

在评论中你可以通过转义字符串来检查:

As in comment you can check this by escaping the string:

... + escape(data) + ...

您还可以使用 data.length 来看看字符串是否是你期望的长度。

You can also use data.length to see if the string is of the length you expect.

你需要找到这个的来源(可能是相关的编码)所以你可以防止字符串以这种方式作为前缀。如果您无法找到源,临时解决方案是在将字符串传递给 parseInt()之前删除字符串,但不建议将其用于最终解决方案。

You need to find the source for this (probably encoding related) so you can prevent the string for being prefixed this way. If you are unable to find the source a temporary solution would be to strip the string before you pass it to parseInt() but this is not recommended for a final solution.

您可以使用例如regEx去除非数字字符:

正则表达式使用javascript返回数字

You can use for example a regEx to strip of the non-numeric chars:
Regex using javascript to return just numbers

(或使用建议的东西在评论中)

(or use something as suggested in the comments)

但最后你会想要找到来源。

But in the end you will want to find the source.

更新感谢@ fero的链接,它表明您获得的字符来自原始文件中的BOM标记,表示字节顺序。

Update thanks to @fero's link it indicates that the char you are getting comes from a BOM marker in your original file to indicate byte-order.

你可以重新开始 - 在没有此标记的情况下编写文件,或者在发送数据之前尝试在服务器端将其剥离。如果您的数据是UTF-8,则不会对数据本身产生影响。

You could re-write your file without this marker or try to strip it off at server side before sending the data. If your data is UTF-8 this won't have an effect on the data itself.

这篇关于Chrome:parseInt()返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆