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

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

本文关键字:循环 迭代 一次 是否 JavaScript 下一个 语句 函数 JQuery      更新时间:2023-09-26

我有这段代码,我希望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');
});

next显然意味着与我预期的不同。

我觉得next退出了$.each,而不是跳过当前键/值。

有没有一种方法可以像我所期望的那样实现next

由于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');
});

我觉得这个更时尚:

$.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');
});

for..inwhile等其他构造不同,$.each不是一种语言构造。使用这些构造,可以使用continue跳过当前元素,使用break退出循环。由于$.each采用回调函数,因此需要使用回调的return值来影响接下来的操作。

返回true,继续下一个项目;返回CCD_ 14以断开循环。

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

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

返回true

来自文档:

我们可以在通过使回调函数返回false。返回非false与for循环中的continue语句;它将立即跳到下一个迭代。

jQuery.each

使用if语句使下一个语句变得不必要。只要在if中做你想做的事,忽略其他的。迭代会自动进行。

使用continue;跳过循环中的下一次迭代。

编辑:是的,很抱歉,我发誓我在那里看到了一个循环:(你可以在jQuery的each()中通过返回一个非false值来"继续",返回对你的情况有效吗?