JavaScript中$.each循环中的非法continue语句

47

我遇到了一个错误,表示有非法的continue语句。 我有一个单词列表,用于表单验证,问题是它将一些子字符串与保留字匹配,因此我创建了另一个干净的单词数组进行匹配。如果匹配到一个干净的单词就继续,否则如果匹配到保留单词就提示用户。

$.each(resword,function(){
        $.each(cleanword,function(){
            if ( resword == cleanword ){
                continue;
            }
            else if ( filterName.toLowerCase().indexOf(this) != -1 ) {
                console.log("bad word");
                filterElem.css('border','2px solid red');
                window.alert("You can not include '" + this + "' in your Filter Name");
                fail = true;
            }
        });
    });
6个回答

95

continue语句适用于普通的JavaScript循环,但是jQuery的each方法需要使用return语句。返回任何非false的值将会表现为continue。返回false时,它将表现为break

$.each(cleanword,function(){
    if ( resword == cleanword ){
        return true;
    }
    else if ( filterName.toLowerCase().indexOf(this) != -1 ) {
        //...your code...
    }
});

了解更多信息,请参阅jQuery文档


3
实际上,jQuery 并不松散地检查它,如果它没有显式地为 false (=== false),它就会继续执行。因此,你可以只是使用 return;,它会返回未定义的值,这将起到 continue 的作用。 - Bob Fincheimer
@Bob - 谢谢,我不是100%确定它是否必须明确为false,还是只要是falsy就可以了。 - James Allardice

10

将 continue 替换为

return true;

4

您正在使用continue语句,该语句是用于JavaScript for循环中的。然而,在jquery的each处理程序中,这将无法正常工作。在jquery的each循环中,相当于continue的语句是返回一个非false值。

if ( resword == cleanword ){
  return true;
}

3
在jQuery.each循环中,必须返回true或false来更改循环迭代:
我们可以通过使回调函数返回false来在特定迭代中断$.each()循环。返回非false与在for循环中使用continue语句相同;它将立即跳过到下一个迭代。
因此,你需要这样做:
$.each(resword,function(){
    $.each(cleanword,function(){
        if ( resword == cleanword ){
            return true;
        }
        else if ( filterName.toLowerCase().indexOf(this) != -1 ) {
            console.log("bad word");
            filterElem.css('border','2px solid red');
            window.alert("You can not include '" + this + "' in your Filter Name");
            fail = true;
        }
    });
});

1
在JQuery的each方法中,每次循环数组时我们都会调用一个函数,因此continue无法使用,我们需要return true来退出函数。 只有在没有匿名函数的简单循环中才能使用continue

-1

你不能在那里使用 continue。它会自动继续执行,只需将其删除 - 我认为根据您的描述应该可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接