gpt4 book ai didi

Javascript array.forEach 作用域?

转载 作者:行者123 更新时间:2023-11-30 17:06:34 25 4
gpt4 key购买 nike

第 9 行的 console.log 显示

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

对于所有 3 个数组元素,即使进行这些更改的循环尚未运行。这怎么可能?

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 ;

}

这是代码的 jsfiddle http://jsfiddle.net/d46wh2cv/7/ .

我在以下位置阅读了规范:

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

但我看不到任何对这种违反直觉的行为的解释。

我正在使用 Google chrome 39.0.2171.95 运行 Debian Linux,并且在 Iceweasel 24.5.0 中也有相同的结果。

感谢您的帮助。

最佳答案

您正在记录对对象的引用(因为数组是全局数组对象的一个​​实例)。

你是对的,循环在日志行时没有运行,但这并不重要。当您检查它时,值已经更改(因为循环可能需要 2 或 3 毫秒才能运行)。

尝试只记录 test[0].count 而不是整个对象。

关于Javascript array.forEach 作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27897227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com