jQuery returnでeach繰り返し処理を途中でスキップするサンプル

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

書式
const オブジェクト名 = {キー1:値1,キー2:値2,…}
$.each(オブジェクト名.function(key,val){
if(条件式){
return;}
})
eachメソッドの繰り返し処理の途中、returnでスキップします。
「return;」を使ってeachメソッドのループの先頭に戻ります。

使用例

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==="大阪"){
//eachメソッドのループの先頭に戻る
return;
}
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==="大阪"){ //eachメソッドのループの先頭に戻る return; } 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==="大阪"){
    //eachメソッドのループの先頭に戻る
            return;
      }
      console.log( key + ": " + val);
});
</script>
</head>
<body>


</body>
</html>

実行結果
11: 東京
33: 福岡

jQuery

Posted by arkgame