繁体   English   中英

for循环中数组长度错误

[英]Wrong length of array in for loop

我在包含对象数组的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
}

问题是日志语句3在第一次迭代中显示了一个包含2个项目的对象数组,但是日志语句4将长度显示为1。

对于这样的两次迭代,日志语句3的输出是相同的,[{latestTimestamp:null,storeName:“ testStore”},{latestTimestamp:null,storeName:“ testStore”}]

哪里应该是第一个循环:

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

第二循环:

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

仅供参考:这可以在Safari中正常运行,但不能在chrome上运行-OSX附加的提琴: http : //jsfiddle.net/gauravsoni/09Ls3rtx/

附件截图: 长度错误

实际上,这是由于Debugger行为引起的

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

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

我认为这就是@yorlin的意思。

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

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

注意 :在控制台中, 斜体值会立即进行评估,而非斜体值在显示时会进行评估(您可以在值旁边的蓝色[i]中看到)。

结论 :在第二张截图中,我们可以清楚地看到它不是Chrome错误。

我已经尝试过了...。就像@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
}

这是由于console.log()的异步性质而发生的,您可以在console.log()上找到有关此行为的更多详细信息异步还是同步?

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

 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 } 

暂无
暂无

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

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