JavaScript for文でオブジェクトのキーと値を取得する

環境
Windows 10 Home 64bit
Google Chrome 107.0.5304.107

構文
const オブジェクト名 = {キー1:値1,キー2:値2,…}
for (const 変数名 in オブジェクト名){処理コード}
「for…in」文を使ってオブジェクトのキーと値を取得します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//オブジェクトの初期化
const user = { age: "22", city: "tokyo", name: "yamada" };
//キーと値を出力
for (const t in user) {
console.log("キー:" + t);
console.log("値:" + user[t]);
}
//オブジェクトの初期化 const user = { age: "22", city: "tokyo", name: "yamada" }; //キーと値を出力 for (const t in user) { console.log("キー:" + t); console.log("値:" + user[t]); }
 //オブジェクトの初期化
const user = { age: "22", city: "tokyo", name: "yamada" };

//キーと値を出力
 for (const t in user) {
    console.log("キー:" + t); 
    console.log("値:" + user[t]);
 }

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> "キー:age"
> "値:22"
> "キー:city"
> "値:tokyo"
> "キー:name"
> "値:yamada"
> "キー:age" > "値:22" > "キー:city" > "値:tokyo" > "キー:name" > "値:yamada"
> "キー:age"
> "値:22"
> "キー:city"
> "値:tokyo"
> "キー:name"
> "値:yamada"

 

JavaScript

Posted by arkgame