Loops in JavaScript-based JavaScript

Source: Internet
Author: User

1. Normal cycle
The usual loop notation in JavaScript is this:

Sub-optimal loopfor (var i = 0; i < myarray.length; i++) {    //do something with Myarray[i]}

The problem with this notation is that each loop needs to read the length property from the MyArray object, which can cause a large performance problem for JavaScript. If myarray are large objects, or DOM objects are more so, because these methods of DOM objects are queried at execution time. Like what:
Document.getelementsbyname ()
Document.getelementsbyclassname ()
document.getElementsByTagName ()
So we should write this:

for (var i = 0, max = myarray.length; i < Max; i++) {    //does something with Myarray[i]}

So we can read max at the beginning of the loop and no longer query from the MyArray object. Of course, if you apply the unique var pattern, we should raise the declaration to the beginning of the function:

function Looper () {    var i = 0,        max,        myarray = [];    // ...    for (i = 0, max = myarray.length; i < Max; i++) {        //does something with Myarray[i]    }}

In doing so we can get the benefit of the unique Var pattern, but the drawback is that the loop body code is not easy to reuse. If we shorten this code further, it can be written in the following two ways:

var i, myarray = []; Subtract Max variables after refinement
for (i = myarray.length; i--;) {
Do something with Myarray[i]
}

var myarray = [],
i = myarray.length;
while (i--) {//using while loop
Do something with Myarray[i]
}

2. For-in Cycle
The for-in loop effectively iterates through the properties in an object, but for-in is generally not used in an array object. In general, for an array object, you should use a normal loop, because For-in uses the meaning on the array object and iterates over the elements in the array. When we use for-in for ordinary objects, we should be careful to filter out the methods in the object, otherwise there will be unexpected problems. For example, the following code uses Object.prototype to add the Clone method to all objects:

The Objectvar man = {    hands:2,    legs:2,    heads:1};//somewhere else in the code//a method is added to Al L Objectsif (typeof  Object.prototype.clone = = = = "undefined") {    Object.prototype.clone = function () {};}

If you use the for-in loop at this point, you must use the hasOwnProperty () method to filter out the methods in the object:

1.//for-in Loopfor (var i in mans) {    if (Man.hasownproperty (i)) {//filter        Console.log (i, ":", Man[i]);    } }/*result in the consolehands:2legs:2heads:1*/

If you do not do this, you might like the following code:

2.//antipattern://for-in loop without checking hasOwnProperty () for (Var i in Mans) {    console.log (i, ":", Man[i]);} /*result in the Consolehands:2legs:2heads:1clone:function () */

The hasOwnProperty () method works for all JavaScript objects, but if the programmer manually redefined the method, the code above will not work. You should use the following improved notation:

for (var i in mans) {    if (Object.prototype.hasOwnProperty.call (man, i)) {//filter        Console.log (i, ":", Man[i]); 
   }}

This improved notation does not call the hasOwnProperty () method with man, but instead uses the prototype of object to invoke it. If you think Object.prototype.hasOwnProperty is too long and looks a bit verbose, you can also use the unique var pattern to define it at the head of the function:

var i,    hasown = Object.prototype.hasownproperty;for (i in Mans) {    if (Hasown.call (man, i)) {//filter        console. Log (I, ":", Man[i]);}    }

In the example above, we use Object Prototypes (Object.prototype) to add methods to all objects, which is very handy, but can also lead to problems with code maintenance. Because other programmers don't necessarily know that you're acting on all the objects. So this practice is not encouraged. If you have to do this, it is recommended to check this before:

if (typeof Object.protoype.myMethod!== "function") {    Object.protoype.myMethod = function () {        //implementation ...    };}

Loops in JavaScript-based JavaScript

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.