Objectとは
配列は数字が添え字のデータセット オブジェクトは文字列が添え字のデータセット
オブジェクトの各要素をループ処理で使用する場合はfor文ではなく for inを使用する。
Objectの宣言方法
- let pokotanObj = new object();
pokotanObj["age"] = 65;
pokotanObj["height"] = 105;
pokotanObj["weight"] = 120;
- let pokotanObj = {};
tensuuObj["adachi"] = 65;
tensuuObj["andou"] = 78;
tensuuObj["utiki"] = 87;
-
let pokotanObj = {"age":65, "height":105, "weight":120};
-
let pokotanObj = { age:65, height:105, weight:120};//この様に省略可
これらの意味合いは同じである
3番目の方法で宣言する場合、要素名が「変数名に使える文字列」の場合”を省略して書くことができる。
各要素の使用方法
- let s = pokotanObj["age"] + "," + pokotanObj.height
document.write(s);
出力結果は 65,105
※.が利用できるのは、その要素名が 変数名に使える文字列のみ
入れ子
配列と同じように、オブジェクト内に入れ子のオブジェクトや配列を作成することができる
-
let nestObj = {};//オブジェクトを定義
nestObj.poko = {age:25,height:105};
nestObj.moko = {age:35,height:110};
console.log(JSON.stringify(nestObj, null, " "));
-
{
"poko": {
"age": 25,
"height": 105
},
"moko": {
"age": 35,
"height": 110
}
}
-
let nestObj = {poko: {age: 25,height: 105}, moko: {age: 35,height: 110}};
console.log(JSON.stringify(nestObj, null, " "));
-
{
"poko": {
"age": 25,
"height": 105
},
"moko": {
"age": 35,
"height": 110
}