JQuery或JavaScript是否有下一个语句/函数可以跳到循环的下一次迭代?

San*_*ing 1 javascript jquery loops next

我有这个代码,我想next跳到下一个迭代.

$.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');
});
Run Code Online (Sandbox Code Playgroud)

next显然意味着与我的期望不同的东西.

它接缝,我认为next退出$.each,而不是跳过当前的键/值.

有没有办法next像我期望的那样做?

Tom*_*lak 7

由于jQuery的性质,没有办法在函数体中声明"next".内部函数不知道它是在循环中执行的,因此不会影响这个事实.

但你可以提前返回,这具有相同的效果:

$.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');
});
Run Code Online (Sandbox Code Playgroud)

我发现这更时尚:

$.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');
});
Run Code Online (Sandbox Code Playgroud)


lon*_*day 6

与其他构造不同,例如for..inwhile,$.each不是语言构造.使用这些构造,您可以使用continue跳过当前元素并break离开循环.由于$.each采用了回调函数,您需要使用回调return值来影响接下来发生的事情.

返回true继续下一个项目; 返回false打破循环.

在这种情况下,您应该使用return true:

else {
   return true; // skip to next element
}
Run Code Online (Sandbox Code Playgroud)