Tag: foreach

For-each over an array in JavaScript

The Question : 4853 people think this question is useful How can I loop through all the entries in an array using JavaScript? I thought it was something like this: Where theArray is my array, but this seems to be incorrect. The Question Comments : answers to this question are discussed at meta The Answer


让我在前面说,我知道什么foreach是,是什么以及如何使用它。这个问题涉及它在引擎盖下如何工作,我不希望有任何答案沿着“这就是你如何循环阵列foreach”的方式。 很长一段时间,我认为这foreach与阵列本身一起工作。然后,我发现它提供了许多与数组副本一起工作的事实,并且我认为这是故事的结尾。但是我最近就这个问题进行了讨论,经过一些实验后发现这实际上并不是100%真实的。 让我表明我的意思。对于以下测试用例,我们将使用以下数组: $array = array(1, 2, 3, 4, 5); 测试案例1: foreach ($array as $item) { echo "$item\n"; $array = $item; } print_r($array); /* Output in loop: 1 2 3 4 5 $array after loop: 1 2 3 4 5 1 2 3 4 5 */ 这清楚地表明我们并不直接处理源数组 – 否则循环会一直持续下去,因为我们在循环过程中不断地将项目推送到数组上。但是可以肯定的是这种情况: 测试案例2: foreach ($array as $key =>

Which is more performant for/forEach if we are accessing current item in loop?

问题内容: Every where people are saying for is more performant then forEach e.g. https://jsperf.com/for-vs-foreach/37 Javascript efficiency: ‘for’ vs ‘forEach’ But does it holds true when accessing current element in loop. If not why not if yes what about following code, which gives contradictory results in different cases: Logic: //---------------------------------------- var arr = , len =

Javascript/NodeJS: Array empty after pushing values in forEach loop

问题内容: I got a little bit of a problem. Here is the code: Situation A: var foundRiders = ; riders.forEach(function(rider){ Rider.findOne({_id: rider}, function(err, foundRider){ if(err){ console.log("program tried to look up rider for the forEach loop finalizing the results, but could not find"); } else { foundRiders.push(foundRider); console.log(foundRiders); } }); }); Situation B var foundRiders =