简体   繁体   English

如何在JavaScript中将JSON数组值转换为整数(来自php / mysql)

[英]How to cast JSON array values as integers in javascript (from php / mysql)

I have a php page which gets some data in mysql database and return a json file, and then I call this json file with an ajax call : 我有一个php页面,该页面在mysql数据库中获取一些数据并返回json文件,然后用ajax调用来调用此json文件:

$.ajax({
        type: "POST",
        dataType: "json",
        url: "get_players_stats.php", //Relative or absolute path to players_stats file
        success: function(data) {
            var list = [];
            $.each(data, function() {
                list.push([this.time, this.playersonline]);
            })
            console.log(list);

        }
    });

the console.log(list); console.log(list); shows me this : 告诉我这个:

[["-1009843200000", "1"], ["-252460800000", "2"], ["-94694400000", "3"], ["31536000000", "2"],....

but instead I want it to look like this : 但是我希望它看起来像这样:

[[-1009843200000, 1], [-252460800000, 2], [-94694400000, 3], [31536000000, 2],....

How can I do that ? 我怎样才能做到这一点 ?

Could you just do something as simple as this? 您能做些简单的事情吗?

$.each(data, function() {
    list.push([Number(this.time), Number(this.playersonline)]);
}

This is a type conversion problem : your data is showing as text format and you want it as number format. 这是类型转换问题 :您的数据以文本格式显示,而您希望以数字格式显示。

You could parse the text as float in javascript, but that would likely be very inefficient, when instead you could cast the data as the type you need in the SQL query that returns the JSON. 您可以在javascript中将文本解析为float,但这可能效率很低,相反,您可以将数据强制转换为返回JSON的SQL查询中所需的类型。

To get you more details on how, it would be good to see how you pull the data into the JSON in the first place. 为了让您更详细地了解如何操作,最好首先查看如何将数据提取到JSON中。

EDIT: 编辑:

the actual answer you should be using is here: PHP json_encode encoding numbers as strings 您应该使用的实际答案是: PHP json_encode将数字编码为字符串

Do you really need to convert those values to numeric ones? 您是否真的需要将这些值转换为数字值? JavaScript only supports 53 bit integers, so parseInt('10765432100123456789') will be converted to 10765432100123458000 integer. JavaScript仅支持53位整数,因此parseInt('10765432100123456789')将转换为10765432100123458000整数。

Working with large integers in JavaScript . 在JavaScript中使用大整数

If you still would like to convert the response you can do something like this: 如果您仍想转换响应,则可以执行以下操作:

$.each(data, function() {
  list.push([+this.time, +this.playersonline]);
})

ES6 syntax http://jsbin.com/qamoru/edit?js,console ES6语法http://jsbin.com/qamoru/edit?js,控制台

 let arr=[["-1009843200000", "1"], ["-252460800000", "2"], ["-94694400000", "3"], ["31536000000", "2"]]; let newArr = arr.map((item)=> item.map((it)=> Number(it))); console.log(newArr) 

JS Bin on jsbin.com jsbin.com上的JS Bin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM