jQuery each()で配列をループで処理するサンプル

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

構文
const 配列の変数名 = [要素1, 要素2,…];
$.each配列の変数名, function(index, value){処理コード}
jQuery.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.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btns").click(function(){
const city = ['tokyo', 'oosaka', 'fukuoka'];
$.each(city, function(index, ct){
console.log(index + ': ' + ct);
});
});
});
</script>
</head>
<body>
<p>
<input type="button" id="btns" value="表示"></p>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btns").click(function(){ const city = ['tokyo', 'oosaka', 'fukuoka']; $.each(city, function(index, ct){ console.log(index + ': ' + ct); }); }); }); </script> </head> <body> <p> <input type="button" id="btns" value="表示"></p> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btns").click(function(){
     const city = ['tokyo', 'oosaka', 'fukuoka'];
     $.each(city, function(index, ct){
     console.log(index + ': ' + ct);
    });
  });
});
</script>
</head>
<body>
<p>
<input type="button" id="btns" value="表示"></p>
</body>
</html>

実行結果
「表示」ボタンを押すと、コンソールに下記メッセージが表示されます。
0: tokyo
1: oosaka
2: fukuoka

jQuery

Posted by arkgame