请帮助我理解这段JavaScript代码段中的“while”循环
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了请帮助我理解这段JavaScript代码段中的“while”循环,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2550字,纯文字阅读大概需要4分钟。
内容图文
![请帮助我理解这段JavaScript代码段中的“while”循环](/upload/InfoBanner/zyjiaocheng/783/016410ca53f341b3bea33345bb539816.jpg)
我看过这样一个片段,用于在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 totrue
,statement
is executed. When condition evaluates tofalse
, execution continues with the statement after thewhile
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 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代码段中的“while”循环全部内容,希望文章能够帮你解决请帮助我理解这段JavaScript代码段中的“while”循环所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。