Example
What is the output value of mean in the following code?
var scores=[98,74,85,77,93,100,89];var total=0;for(var score in scores){ total+=score;}var mean=total/scores.length;mean;//? 17636.571428571428
Use the calculator to calculate manually, the answer should be 88. The real result of this code should be 88, but why is the actual result incorrect? This and for...in loops enumerate all keys, including those in the prototype. In other words, the above code should actually be (0+1+2+...+6)/7=21, but it's not. The key here is even the index of the array, and the object property is always a string. As a result, the "+ =" operator performs a connection operation of the string. The result is that the value of total is "00123456". Mean the final result is 17636.571428571428. A result that cannot be understood.
Use a traditional for loop
var scores=[98,74,85,77,93,100,89];var total=0;for(var i=0,n=scores.length;i < n;i++){
This method ensures that you need an integer index and array element to get to them, and never confuse them or throw a string cast. In addition, it ensures the correct number of iterations and does not accidentally include non-integer attributes stored in an array object or in its prototype chain.
Watch out.
The use of the variable n in the loop above can be used in the loop without having to get the length of the array one time.
Send a message to the programmer reading the code: The loop termination condition is simple and deterministic.
Tips
Indexed properties of an iterative group should always use a for loop instead of a for...in loop
Consider storing the length of the array in a local variable before the loop to avoid recalculating the array length
[Effective JavaScript note] 49th: array iterations take precedence over a for loop instead of for...in loop