「jQuery」eachメソッドで配列を繰り返し処理するサンプル
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.0
書式
$.each(配列,function(index,val) {
// 繰り返す処理
});
配列の要素1つずつに対して処理を行います。
functionの1つめの引数はインデックスです。
functionの2つめの引数は要素です。
eachメソッドで1つ目の引数にある配列の要素の数分を順にチェックします。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//ボタン動作
$("#btnchk").click(function() {
const cityArr= ["東京","大阪","福岡"];
$.each(cityArr,function(index,val) {
alert( index + ": " + val);
});
});
});
</script>
</head>
<body>
<p>
<input type="button" value="検証" id="btnchk" /></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//ボタン動作
$("#btnchk").click(function() {
const cityArr= ["東京","大阪","福岡"];
$.each(cityArr,function(index,val) {
alert( index + ": " + val);
});
});
});
</script>
</head>
<body>
<p>
<input type="button" value="検証" id="btnchk" /></p>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ //ボタン動作 $("#btnchk").click(function() { const cityArr= ["東京","大阪","福岡"]; $.each(cityArr,function(index,val) { alert( index + ": " + val); }); }); }); </script> </head> <body> <p> <input type="button" value="検証" id="btnchk" /></p> </body> </html>
実行結果
「検証」ボタンを押すと、「0: 東京」、「1: 大阪」、「2: 福岡」を出力します。