开发者

for in construct

开发者 https://www.devze.com 2023-02-07 04:13 出处:网络
I recently stumbled upon this construct in Javascript: function find(id) { var found = null; findloop: for (var index in products){

I recently stumbled upon this construct in Javascript:

function find(id) {
  var found = null;

  findloop: for (var index in products){
    var product = products[index];
    if (product.id === id) {
      found = product;
      break findloop;
    }
  };
  r开发者_开发技巧eturn found;
}

What bothers me is the findloop: Is this even a legal syntax ? What is the point of it ?

thanks


Here, findloop: is a label. It can be referred to by break (as it is in your example), which can be useful when you have nested loops, and you want to break out of (one of) the outer loop(s).

In this case, it serves no useful purpose, since there is only one loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消