【发布时间】:2015-03-09 22:31:06
【问题描述】:
第 9 行的 console.log 显示
{ '计数' : 1111111 , '平均' : 2222222 , '总计' : 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 ;
}
这是代码 http://jsfiddle.net/d46wh2cv/7/ 的 jsfiddle。
我在以下位置阅读了规格:
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 中也有相同的结果。
感谢您的帮助。
【问题讨论】:
-
可能是 This 和其他几个的副本。
标签: javascript arrays foreach scope