开发者

Does JQuery or JavaScript have a next statement/function to skip to the next iteration of a loop?

I have t开发者_开发问答his code, where I would like that next skips to next iteration.

$.each(result, function(key, value) {

    if (value.type == "individuel") {
    cform["IN"] = "checked";
    } else if (value.type == "course") {
    cform["CO"] = "checked";
    } else {

    next;

    }

    cform["ID"]     = key;
    cform["title"]  = value.title;

    $('#template').tmpl(cform).appendTo('#content');
});

But next apparently means something different from what I would expect.

It seams to me that next exits the $.each rather than skipping the current key/value.

Does there exist a way to do next like I would expect?


Due to the nature of jQuery, there is no way to state a "next" in the function body. The inner function does not know that it is being executed in a loop and can therefore not influence this fact.

But you can return early, which has the same effect:

$.each(result, function(key, value) {
  if (value.type == "individuel") {
    cform["IN"] = "checked";
  } else if (value.type == "course") {
    cform["CO"] = "checked";
  } else {
    return true;
  } 

  cform["ID"]     = key;
  cform["title"]  = value.title;
  $('#template').tmpl(cform).appendTo('#content');
});

I find this more stylish:

$.each(result, function(key, value) {
  switch (value.type) {
    case "individuel": cform["IN"] = "checked"; break;
    case "course":     cform["CO"] = "checked"; break; 
    default: return true;
  }

  cform["ID"]     = key;
  cform["title"]  = value.title;
  $('#template').tmpl(cform).appendTo('#content');
});


Unlike other constructs, such as for..in and while, $.each is not a language construct. With those constructs, you can use continue to skip the current element and break to leave the loop. Since $.each takes a callback function, you need to use the callback's return value to affect what happens next.

Return true to continue to the next item; return false to break the loop.

In this case, you should use return true:

else {
   return true; // skip to next element
}


return true;

From the docs:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

jQuery.each


Using the if statement makes the next unnecessary. Simply do whatever you want in the if and ignore the else. The iteration moves on automatically.


Use continue; to skip to the next iteration in a loop.

Edit: Yep, sorry about that I swear I saw a loop in there :( You can "continue" in jQuery's each() by returning a non-false value, will a return work for your case?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜