オブジェクトのプロパティを列挙する
const person1 = {
name: 'Tom',
age: 17
}
const person2 = Object.create(person1);
person2.name = 'Huck';
for(let p in person2) console.log(p); // -> "name" "age"
person2.sayHello = function() {console.log(`Hello ${this.name}`)};
for(let p in person2) console.log(p); // -> "name" "sayHello" "age"
// オブジェクト独自のプロパティのみを表示する
for(let p in person2) {
if(!person2.hasOwnProperty(p)) continue;
console.log(p);
}
// -> "name" "sayHello"
// メソッドは除外する
for(let p in person2) {
if(typeof(p) === 'function') continue;
console.log(p);
}
// -> "name" "sayHello" "age"
// 独自プロパティかつ列挙可能なプロパティを表示
const group = {groupName: 'Tennis circle'};
const person3 = Object.create(group);
person3.name = 'Tom';
person3.age = 17;
person3.sayHello = function() {console.log(`Hello ${this.name}`)};
Object.defineProperty(person3, 'sayHello', {
enumerable: false
});
console.log(Object.keys(person3)); // -> ["name", "age"]
const p = Object.keys(person3);
for(let i=0; i<p.length; i++) console.log(person3[p[i]]);