やあ子供たち。今日はこんなプログラムを書いて遊んでみたので紹介するよ。
結論から言うと「配列は、for.. of 構文で回そう。for .. in 構文は、オブジェクトの各フィールドを巡れるが、あまり使わなさそうだな」だ。
(みてほしいのはもちろん以下の「script」節の中身だぞ。)
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Cache-Control"content="no-cache"> <title>This is Tab TItle</title> </head> <body> <!-- HTML部品設置を記述 --> <h4 id="hello">Hello HTML.</h4> <script type="text/javascript"> // ***javascriptのプログラムを記述*** window.addEventListener("DOMContentLoaded",function(){ }); let arr=[ {name: "apple", price: 150}, {name: "apricot", price: 400}, {name: "orange", price: 150}, {name: "muscat", price:1280}, {name: "melon", price: 1280}, ]; function textout( str ) { let h5 = document.createElement("textContent"); h5.textContent = str; let hello = document.getElementById("hello"); hello.appendChild(h5); hello.appendChild( document.createElement("br")); return; } function dump( arr) { textout(" -- "); for( let item of arr )// for..ofループ(Isn't it Handy!) textout( item.name + ", " + item.price ); textout(" -- "); return; } textout(); dump( arr ); let cnt=0; for( let item of arr )// for..ofループ(Isn't it Handy!) { ++cnt; item.name = "tako"+cnt; let str=""; str += item.name + " "; str+="{"; for( key in item )// for..ofループ(might be useful in some cases..) str+= " "+ key + ": "+ item[key]; str+="}"; textout(str); } dump( arr ); </script> </body> </html>
さあ、上記コードをa.htmlとして保存してChromeブラウザで見て見ると以下のような出力が見れるぞ。果物の名前が全部takoに書き換わっていることから、循環変数を更新することで実際の配列要素自体を更新できていることが確認できるね。
Hello HTML. -- apple, 150 apricot, 400 orange, 150 muscat, 1280 melon, 1280 -- tako1 { name: tako1 price: 150} tako2 { name: tako2 price: 400} tako3 { name: tako3 price: 150} tako4 { name: tako4 price: 1280} tako5 { name: tako5 price: 1280} -- tako1, 150 tako2, 400 tako3, 150 tako4, 1280 tako5, 1280 --
じゃあ今日はこんなところで。チャオ!