javascript$.each循环中的continue语句非法
我得到一个错误,这有一个非法的continue语句。 我有一个要检查表单验证的单词列表,问题是它将一些子字符串与保留单词匹配,所以我创建了另一个要匹配的干净单词数组。如果它匹配一个干净的字,则继续;如果它匹配一个保留字,则通知用户javascript$.each循环中的continue语句非法,javascript,jquery,Javascript,Jquery,我得到一个错误,这有一个非法的continue语句。 我有一个要检查表单验证的单词列表,问题是它将一些子字符串与保留单词匹配,所以我创建了另一个要匹配的干净单词数组。如果它匹配一个干净的字,则继续;如果它匹配一个保留字,则通知用户 $.each(resword,function(){ $.each(cleanword,function(){ if ( resword == cleanword ){ 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;
}
});
});
替换为“继续”
return true;
continue
语句对于正常的JavaScript循环来说是很好的,但是jQueryeach
方法要求您使用return
语句。返回任何非false的内容,它将作为一个continue
。返回false,它将作为一个中断
:
$.each(cleanword,function(){
if ( resword == cleanword ){
return true;
}
else if ( filterName.toLowerCase().indexOf(this) != -1 ) {
//...your code...
}
});
有关更多信息,请参阅您正在使用的。这行不通。jquery
中的continue
的等价项是返回一个非false值
if ( resword == cleanword ){
return true;
}
在jQuery.each循环中,必须返回true或false以更改循环交互:
我们可以通过使
回调函数返回false。返回非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;
}
});
});
你不能在那里使用continue。不管怎样,它都会自动继续,只需删除它-我认为它应该按照您的描述工作。在Jquery中,每次在数组中循环时,我们调用函数的每个方法,因此continue
将不起作用,我们需要返回true
才能从函数中退出。
只有在没有匿名函数的简单循环中,我们才可以使用continue
实际上,jQuery不会松散地检查它,如果它不是显式的false(==false
),那么它将继续。因此,您只需执行返回代码>,它将返回未定义的,作为continue。@Bob-谢谢,我不能100%确定它是显式为false,还是falsy。