为什么我的JSON对象在操作之前会发生变化?

时间:2014-02-26 19:08:35

标签: javascript jquery json parsing typeof

这是我的代码:

var data = $.parseJSON('[{"Date":"2014-02-19","Count":"963"},{"Date":"2014-02-20","Count":"2638"}]');
console.log(data);
console.log(typeof data[0].Count);
data.forEach(function(d) {
    d.Count = +d.Count;
});
console.log(typeof data[0].Count);

第一个控制台日志将我的Counts视为每个对象内的数字。

第二个控制台日志是字符串。

最终的console.log是数字。

有人可以向我解释为什么第一个控制台日志会将每个Count视为一个数字,当我在使用d.Count = + d.Count代码行将Count操作为数字之前记录数据对象时?

以下是其中代码的小提琴:http://jsfiddle.net/b73fZ/

3 个答案:

答案 0 :(得分:1)

我认为这与控制台输出关于对象的时间有关。看看这些:

如果您正在使用Chrome / webkit,您可能会在显示三角形(“twistie”)附近看到“小蓝i”,其工具提示显示在开发人员首次扩展扭曲时填充数据。我稍微修改了你的jsFiddle示例here,你可以看到输出是你所期望的:

var data = $.parseJSON('[{"Date":"2014-02-19","Count":"963"},{"Date":"2014-02-20","Count":"2638"},{"Date":"2014-02-21","Count":"1962"},{"Date":"2014-02-22","Count":"1122"},{"Date":"2014-02-23","Count":"1192"},{"Date":"2014-02-24","Count":"2204"},{"Date":"2014-02-25","Count":"1906"},{"Date":"2014-02-26","Count":"1362"}]');
console.log(data);                  // (twistie) [Object, Object, Object, Object, Object, Object, Object, Object]
$.each(data, function () {
    console.log(this);              // Object {Date: "2014-02-19", Count: "963"}, Object {Date: "2014-02-20", Count: "2638"}, ... 
});
console.log(typeof data[0].Count);  // string
data.forEach(function (d) {
    d.Count = +d.Count;
});
console.log(typeof data[0].Count);  // number

答案 1 :(得分:0)

尝试

var data = $.parseJSON('[{"Date":"2014-02-19","Count":"963"},{"Date":"2014-02-20","Count":"2638"},{"Date":"2014-02-21","Count":"1962"},{"Date":"2014-02-22","Count":"1122"},{"Date":"2014-02-23","Count":"1192"},{"Date":"2014-02-24","Count":"2204"},{"Date":"2014-02-25","Count":"1906"},{"Date":"2014-02-26","Count":"1362"}]');
data.forEach( function (d) {
    Object.keys(d).forEach (function (e) {
        document.write(e + ' ' + typeof e + ' ');
    })
    document.writeln("<br>");
});
document.writeln("<br>"+typeof data[0].Count);
data.forEach(function(d) {
    d.Count = +d.Count;
});
document.writeln("<br>"+typeof data[0].Count);

Date string Count string 
Date string Count string 
Date string Count string 
Date string Count string 
Date string Count string 
Date string Count string 
Date string Count string 
Date string Count string 

string 
number 

你会看到它可能是一个console.log错误,正如评论所示。

答案 2 :(得分:0)

当你使用console.log(数据)时,数据对象在所有修改之后都有值,这意味着已经应用了forEach,因此它显示了Count作为数字。

让我用一个例子来解释

var data = $.parseJSON('[{"Date":"2014-02-19","Count":"963"},{"Date":"2014-02- 20","Count":"2638"}]');
    console.log(data);                  //The log will show you 20 rather than 963.
    data[0].Count = 20;                 //Modify the object

在示例中,我们首先控制数据,我们期望Count的值为963,但值为20.

因此,第一个控制台日志将Counts视为数字,因为您在foreach中对其进行了修改。