我见过这样的代码片段,用于使用条件注释在 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;
}());
上面给出的是Paul Irish 记录(并略有改进)版本 on a 詹姆斯·帕多尔西摘录。我发布评论版本是为了让您知道,如果有人可能需要更简单的解释。
我真的很想知道while 循环内发生了什么。我不明白。
(假设我没有把这件事搞砸)while
循环等效于以下内容:
var elt;
do
{
v++;
div.innerHTML = '<!--[if gt IE ' + v + ']><i></i><![endif]-->'
elt = div.getElementsByTagName('i')[0];
} (while elt);
mdc 或任何好的内容是否涵盖了 while(stmt1, stmt2) 的事情。
MDC 是这样说的while:
while (condition)
statement
condition
在每次循环之前评估的表达式。如果此条件评估为true
, statement
被执行。当条件评估为false
,继续执行后面的语句while
loop.
我们可以准确地找出什么是表达来自 MDC 的 JavaScript:
An 表达是任何有效的文字、变量、运算符和计算结果为单个值的表达式的集合;该值可以是数字、字符串或逻辑值。
从概念上讲,有两种类型的表达式:将值分配给变量的表达式和仅具有值的表达式。例如,表达式x = 7
是一个将值 x 赋值为 7 的表达式。该表达式本身的计算结果为 7。此类表达方式使用赋值运算符。另一方面,表达式3 + 4
简单地评估为七;它不执行任务。此类表达式中使用的运算符简称为运营商.
如果您有勇气,还可以查看ECMA-262 语言规范,特别是以下部分:
-
11表达方式,特别是11.14逗号运算符 (
,
)
-
12.6.2 The
while
陈述
Sorry I can't provide direct links as it's all inside of a PDF.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)