编程语言
首页 > 编程语言> > 请帮助我理解这段JavaScript代码段中的“while”循环

请帮助我理解这段JavaScript代码段中的“while”循环

作者:互联网

我看过这样一个片段,用于在JavaScript中使用条件注释检测IE.

var ie = (function(){

    var undef, v = 3, div = document.createElement('div');

    // the while loop is used without an associated block: {}
    // so, only the condition within the () is executed.

    // semicolons arent allowed within the condition,
    //   so a comma is used to stand in for one
    // basically allowing the two separate statements 
    //   to be evaluated sequentially.

    while (
        div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
        div.getElementsByTagName('i')[0]
    );

    // each time it's evaluated, v gets incremented and
    //   tossed into the DOM as a conditional comment
    // the i element is then a child of the div.

    // the return value of the getEBTN call is used as 
    //   the final condition expression
    // if there is an i element (the IE conditional
    //   succeeded), then getEBTN's return is truthy
    // and the loop continues until there is no 
    //   more i elements.

    // In other words:  ** MAGIC**

    return v > 4 ? v : undef;

}());

上面给出的是snippet by James Padolsey上的documented (and slightly improved) version by Paul Irish.我发布了评论版本,让你知道如果有人可能需要更简单的解释.

我真的很想知道while循环中发生了什么.我不明白.

解决方法:

(假设我没有把这个搞得很糟糕)while循环等同于以下内容:

var elt;

do
{
    v++;
    div.innerHTML = '<!--[if gt IE ' + v + ']><i></i><![endif]-->'
    elt = div.getElementsByTagName('i')[0];
} (while elt);

does mdc or any good ones cover this while(stmt1, stmt2) thing.

以下是MDC对while所说的内容:

06001

condition
An expression evaluated before each pass through the loop. If this condition evaluates to true, statement is executed. When condition evaluates to false, execution continues with the statement after the while loop.

我们可以从MDC中找到JavaScript中expression的确切内容:

An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value; the value can be a number, a string, or a logical value.

Conceptually, there are two types of expressions: those that assign a value to a variable, and those that simply have a value. For example, the expression x = 7 is an expression that assigns x the value seven. This expression itself evaluates to seven. Such expressions use assignment operators. On the other hand, the expression 3 + 4 simply evaluates to seven; it does not perform an assignment. The operators used in such expressions are referred to simply as operators.

如果您有勇气,还可以查看ECMA-262 language specification,具体如下:

> 11个表达式,特别是11.14逗号运算符(,)
> 12.6.2 while声明

抱歉,我无法提供直接链接,因为它全部在PDF中.

标签:javascript,code-snippets
来源: https://codeday.me/bug/20190630/1338704.html