Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

html - Colon within a Javascript function while loop

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...