[Effective JavaScript note] 49th: array iterations take precedence over a for loop instead of for...in loop

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.