我见过这样的片段,用于使用条件注释在 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;
}());
上面给出的是documented (and slightly improved) version by Paul Irish在 snippet by James Padolsey 上.我发布评论版本是为了让您知道我可能需要更简单的解释。
我真的很想知道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
的评价:
while (condition) statement
condition
An expression evaluated before each pass through the loop. If this condition evaluates totrue
,statement
is executed. When condition evaluates tofalse
, execution continues with the statement after thewhile
loop.
我们可以准确地找出 expression 是什么 是来自 MDC 的 JavaScript:
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 expression3 + 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 - 请帮我理解这个 JavaScript 片段中的 "while"循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6223333/