for循环中的数组长度错误

时间:2015-10-05 08:17:25

标签: javascript

我在包含对象数组的for循环中面临一个奇怪的行为

以下是示例

var store = {};
var storesWithTimestamps = [];

for (var i=0;i<2;i++){                      
    console.log("inital list",storesWithTimestamps); //1
    console.log("inital length",storesWithTimestamps.length); //2

    store = {};
    store.latestTimestamp = null;
    store.storeName = "testStore";
    storesWithTimestamps.push(store);

    console.log("new list",storesWithTimestamps); //3
    console.log('new length',storesWithTimestamps.length); //4
}

问题是log语句3显示第一次迭代中有2个项目的对象数组,但是log语句4显示长度为1。

对于这样的迭代,log语句3的输出是相同的, [{latestTimestamp:空,STORENAME:&#34; testStore&#34;},{latestTimestamp:空,STORENAME:&#34; testStore&#34;}]

应该在哪里 第一轮:

[{latestTimestamp:null,storeName:"testStore"}]

第二循环:

[{latestTimestamp:null,storeName:"testStore"},{latestTimestamp:null,storeName:"testStore"}]

仅供参考:这在Safari中可以正常使用,但在Chrome-OSX上却没有 附上小提琴:http://jsfiddle.net/gauravsoni/09Ls3rtx/

附加屏幕截图:wrong length

3 个答案:

答案 0 :(得分:2)

实际上这是由于调试器行为

如果在运行脚本时打开调试器,则控制台中的输出将是正确的。

如果在运行脚本时未打开调试器,则会在显示控制台时评估对象。这就是你可以在数组中看到2个对象的原因。

我认为这是@yorlin的意思。

附录: 您可能希望使用JSON.stringify()方法记录即时对象属性:

console.log( "inital list:", JSON.stringify( storesWithTimestamps ) ) //1
...
console.log( "new list:", JSON.stringify( storesWithTimestamps ) ) //3

Nota bene : 在控制台中,斜体值立即被评估,而非斜体值在显示时被评估(正如您在值旁边的蓝色 [i] 中看到的那样) )。

结论: 在第二个发布的屏幕截图中,我们可以清楚地看到它不是Chrome错误。

答案 1 :(得分:1)

我试过这个......就像@yorlin和@Supersharp说的那样。

您可以更清楚地在控制台中查看它。

var store = {};
var storesWithTimestamps = [];

//Checkout the status of ary
function displayObj(objAry){
    var info="\n";
    for(var i=0;i<objAry.length;i++){
        var data=objAry[i];
        info+='\t\trecord('+i+').id:'+data.id+'\n';
    }
    return info;
}

for (var i=0;i<2;i++){                      
    console.log("inital list",storesWithTimestamps); //1
    console.log("inital length",storesWithTimestamps.length); //2

    //put an id to identify
    store = {id:i};
    store.latestTimestamp = null;
    store.storeName = "testStore";
    storesWithTimestamps.push(store);

    console.log("new list",displayObj(storesWithTimestamps)); //3
    console.log('new length',storesWithTimestamps.length); //4
}

答案 2 :(得分:1)

由于console.log()的异步特性,这种情况正在发生 您可以在console.log() async or sync?

找到有关此行为的更多详细信息

您可以尝试解决方法以记录正确的值,如下所示 -

var store = {};
var storesWithTimestamps = [];

for (var i=0;i<2;i++){                      
    console.log("inital list",storesWithTimestamps); //1
    console.log("inital length",storesWithTimestamps.length); //2

    store = {};
    store.latestTimestamp = null;
    store.storeName = "testStore";
    storesWithTimestamps.push(store);

    console.log("new list",JSON.stringify(storesWithTimestamps)); //3 instead of passing object, pass serialized snapshot of the object
    console.log('new length',storesWithTimestamps.length); //4
}

相关问题