JavaScriptでオブジェクト内の全てのプロパティ(キー)に反復処理を行う方法

mail IT

for文の中でinを使用することで、オブジェクト内のプロパティ全てを指定することが可能です。

スポンサーリンク

オブジェクト内のプロパティに反復処理

キーに反復処理

//JavaScript
function objectTest(){
const ob = {
    name: "test",
    point: 10,
    survive: true
};
}
おさらいすると、{}で閉じた中にプロパティと値を,で区切って指定します。
//JavaScript
function objectTest(){
const ob = {
    name: "test",
    point: 10,
    survive: true
};
for(let key in ob){
alert(key);
}
}
作ったオブジェクトの各キーには、for(let 変数 in オブジェクト名)という構文で反復してアクセスできます。ここではキーをひとつずつポップアップさせています。
click me!
実行するとこうなります。

プロパティの値に反復処理

//JavaScript
function objectTest2(){
const ob = {
    name: "test",
    point: 10,
    survive: true
};
for(let key in ob){
alert(ob[key]);
}
}
今度はプロパティのキーではなく、値にそれぞれアクセスしてみます。
オブジェクトの値はオブジェクト名[キーを格納した変数]という構文でアクセスできるので、
click me!
上の式を実行すれば、プロパティの各値に一度ずつアクセスできることが確認できます。
JavaScriptの使い方・メソッド・プロパティまとめ
HTML/CSSとセットでフロントエンドエンジニア三種の神器のひとつ、JavaScript系の記事まとめです。

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny

モバイルバージョンを終了