jQuery return falseでeach繰り返し処理を途中で抜けるサンプル

環境
Windows 10 home 64bit
jQuery 3.6.1

書式
const オブジェクト名 = {キー1:値1,キー2:値2,…}
$.each(オブジェクト名.function(key,val){
if(条件式){
return false;}
})
eachメソッドは、繰り返し処理の途中、return falseでループを抜けます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
const city = {
11:"東京",
22:"大阪",
33:"福岡"
}
$.each(city,function(key,val) {
if(val==="大阪"){
//ループ処理を抜ける
return false;
}
console.log( key + ": " + val);
});
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> const city = { 11:"東京", 22:"大阪", 33:"福岡" } $.each(city,function(key,val) { if(val==="大阪"){ //ループ処理を抜ける return false; } console.log( key + ": " + val); }); </script> </head> <body> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
const city = {
      11:"東京",
      22:"大阪",
      33:"福岡"
}

$.each(city,function(key,val) {
      if(val==="大阪"){
    //ループ処理を抜ける
            return false;
      }
      console.log( key + ": " + val);
});
</script>
</head>
<body>


</body>
</html>

実行結果
11: 東京

jQuery

Posted by arkgame