this series as effective JavaScript 's reading notes.
Can you see what the last average is for this code?
var = [98, scores, Max, Max, 89];var, max = 0;for (var score in scores) {total + = score;} var mean = Total/scores.length;mean; // ?
by calculation, the final result should be the .
but don't forget toFor : InchLoop, is traversed forever isKey, but notvalue, the same is true for arrays. Therefore the aboveFor : Inchin the Loopscorenot expected.98, Abouta series of values, but0,1A series of indexes.
So you might think that the final result is:
(0 + 1+ ... + 6)/7 =
But the answer is also wrong. Another key point is that for: the type of the key in the in loop is always the string type, so the + operator here performs the concatenation of the string actually:
finally get the Total is actually a string 00123456 . This string is converted to a numeric type after the value is 123456, and then divided by the number of elements 7, the final result is obtained:17636.571428571428
so, for array traversal, use the standard for Cycle Best:
var scores = [98, n, a, 0, 89];var total = 0;for (var i =, n = scores.length; i < N.; i++) {Total + = Score S[i];} var mean = Total/scores.length;mean; 88
after all, for this for loops, developers are no longer familiar with it. The index variable i is never treated as a value. The standard for Loop also guarantees the order of the loops, ensuring that this is important for the arithmetic operations of floating-point numbers.
in the above code, a small optimization is also applied. is to calculate the length of the array as the loop boundary before the loop begins. When you do not add / remove element operations to the array itself in the For loop , you can slightly improve performance so that the length of the collection is not queried for Each loop.
Summarize:
- when iterating through an array, use the standard for Loop instead of using the For : in Loop.
- Consider pre-saving the length of the array where necessary to improve performance.
Effective JavaScript Item 49 takes precedence over the for loop for array traversal, not for. In loop