简体   繁体   English

Javascript array.forEach范围?

[英]Javascript array.forEach Scope?

The console.log on line 9 shows 第9行的console.log显示

{ 'count' : 1111111 , 'average' : 2222222 , 'total' : 3333333 } {'count':1111111,'average':2222222,'total':3333333}

for all 3 array elements even though the loop that makes those changes has not run yet. 对于所有3个数组元素,即使进行这些更改的循环尚未运行。 How is this possible? 这怎么可能?

function test11(){

    var test = [
        { 'count' : 1 , 'average' : 2 , 'total' : 3 } ,
        { 'count' : 10 , 'average' : 20 , 'total' : 30 } , 
        { 'count' : 100 , 'average' : 200 , 'total' : 300 }
    ] ; 

    console.log( test ) ; 

    test.forEach( function( element , service_index , array ){

        array[ service_index ].count = 1111111 ;
        array[ service_index ].average = 2222222 ;
        array[ service_index ].total = 3333333 ;

    });

    console.log( test ) ;

    return ; 

}

Here is a jsfiddle of the code http://jsfiddle.net/d46wh2cv/7/ . 这是代码http://jsfiddle.net/d46wh2cv/7/的jsfiddle。

I read the specs at : 我在阅读规格:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

but I don't see any explanation for this counter intuitive behavior. 但我看不到这种反直觉行为的任何解释。

I am running Debian Linux with Google chrome 39.0.2171.95 and have also had the same result in Iceweasel 24.5.0. 我正在用Google chrome 39.0.2171.95运行Debian Linux,并且在Iceweasel 24.5.0中也具有相同的结果。

Thanks for the help. 谢谢您的帮助。

You're logging a reference to an object (since Arrays are an instance of the global Array object). 您正在记录对对象的引用(因为Array是全局Array对象的实例)。

You're right that the loop hasn't run at the time of the log line, but that doesn't matter. 您说对了,在日志行时循环还没有运行,但这没关系。 By the time you inspect it, the values have already changed (since the loop probably takes all of 2 or 3 milliseconds to run). 在您检查它时,值已经更改(因为循环可能需要2或3毫秒才能全部运行)。

Try logging just test[0].count instead of the whole object. 尝试仅记录test[0].count而不是整个对象。

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

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