开发者

What is the JavaScript while loop doing here?

What is this JavaScript code doing here, specifically the while loop:

function setAjaxLinks(){
    var links = document.body.getElementsByTagName("a");
    var linkL = links.length;

    while (开发者_如何学GolinkL--) {
        if (!links[linkL].href.match('#')) {
            mj.pageLoad(links[linkL]);
        }
    }
}

I'm aware "mj" doesn't really mean anything, but what is the general gist?


It loops through all links (a-tags) on the page from the last to the first (decrementing).

If it finds a link that doesn't have a # symbol in it, it calls the mj.pageLoad function with the link in question as parameter.

Here's a blow by blow:

function setAjaxLinks(){
    //find all <a> tag elements on the page
    var links = document.body.getElementsByTagName("a");
    //get the amount of <a> tags on the page
    var linkL = links.length;
    //loop over all <a> tags on the page from last to first
    while (linkL--) {
        //if the href attribute on the current <a> tag has a # sign in it
        if (!links[linkL].href.match('#')) {
            //then call this function (and from the name of the function convert it to an ajax call) 
            mj.pageLoad(links[linkL]);
        }
    }
}


The expression:

linkL--

decrements linkL by one and returns the previous value of linkL.

The expression:

while (someIntValue) { ... }

runs the body of the loop while someIntValue is not 0. It is equivalent to:

while (someIntValue != 0) { ... }

So:

while (linkL--) { ... }

will run the loop with linkL (inside the loop) varying from its initial value minus one, to zero, inclusive.


This is a reverse while which is faster than "for" in many/most cases: see here for citation: http://blogs.oracle.com/greimer/entry/best_way_to_code_a


It's basically a reverse for loop. Starting at the "top" and counting down until it reaches 0. In situations where the order of execution isn't relevant it's more efficient that a forloop.


Basically it iterates through the collection links, and checks if they include a #.

linkL stores the length of the collection. The while checks the boolean value of this variable, then decrements it by one. So when linkL reaches zero, it will still run, and in the next turn zero will evaluate as false, so it stops.

If you check linkL after the while, it will be -1.


It looks like a page preloader.

The while loop decrements linkL until it reaches 0 and iterates over every a tag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜