Java语言函数while循环内的冒号 [英] Colon within a Javascript function while loop
问题描述
我正在浏览一些HTML5 Javascript演示,并且遇到了我以前从未在语法中见过的东西.查看run函数,并注意在 while循环中如何创建 search 对象符号.感兴趣的行包括15和18.有人可以解释这种语法吗?
function run(){var n = 1;搜索:while(运行中){n + = 1;对于(var i = 2; i< = Math.sqrt(n); i + = 1)如果(n%i == 0)继续搜索;//找到一个素数!postMessage(n);}}
(从此处获取的代码; http://html5demos.com/js/cruncher.js)
这不是对象(文字)符号,它是取模(%
)运算符,以得到除 n/i
,然后检查它是否为0.
I was poking around some HTML5 Javascript demos and came across something I've never seen before in the syntax. Take a look at the run function and notice how the search object notation is made in the while loop. Lines of interest include 15 and 18. Can anyone explain this syntax?
function run() {
var n = 1;
search: while (running) {
n += 1;
for (var i = 2; i <= Math.sqrt(n); i += 1)
if (n % i == 0)
continue search;
// found a prime!
postMessage(n);
}
}
(code taken from here; http://html5demos.com/js/cruncher.js)
This is not object (literal) notation, it is defining a label
.
A label
can be used to give a looping construct a name. The benefits of doing this is that you can create more powerful breaks;
or continues;
by referencing outer loops (by their labels).
Note that how the structure of the program you referenced is a:
search: while () {
for (;;;) {
}
}
... and the author is using continue search;
inside the for
loop to continue the execution of the while loop.
As for what's happening on line 18, if (n % i == 0)
is using the modulo (%
) operator to get the remainder between dividing n / i
, and checking whether it's 0.
这篇关于Java语言函数while循环内的冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!