对javascript获取对象属性的几种方法梳理

1、Object.getOwnPropertyNames()

返回 对象 自身及原型链上所有的属性名的数组

2、Object.keys()

返回 对象 自身及其原型链上可枚举的属性名的数组

3、for (key in object)

与2、Object.keys()相同

4、Ojbect.values()

返回 对象 自身及其原型链上可枚举的属性值的数组

5、for (value of object)

没有实现迭代器(iterable)协议无法会报错

6、Object.entries()

返回 [[属性名,属性值],[属性名,属性值]...] 这样的二维数组

我测试的结果
image

下面是代码,可拿去测试

点击查看代码
class Animal {
    constructor(){
        this.sex = 'male';
        this.height = 180;
    }
    sleep(){
        console.log('呼呼呼,睡大觉');
    }
    run(){
        console.log('四条腿,跑得快');
    }
    animalProtoTypeAttribute1 = '这里是Animal原型上的属性1';
    animalProtoTypeAttribute2 = '这里是Animal原型上的属性2';
}
class Person extends Animal {
    constructor(){
        super();
        this.name = '我是人';
        this.age = '18';
    }
    speak(){
        console.log('瓜拉拉,复读机');
    }
    run(){
        console.log('两条腿,耐力强');
    }
    personPrototypeAttribute1 = '这里是Person原型上的属性1';
    personPrototypeAttribute2 = '这里是Person原型上的属性2';
}

var lsh = new Person();


//先获取,在传回修改
var sexDesc = Object.getOwnPropertyDescriptors(lsh,'sex');
var ageDesc = Object.getOwnPropertyDescriptors(lsh,'age');
var animalProtoTypeAttribute2Desc = Object.getOwnPropertyDescriptor(lsh,'animalProtoTypeAttribute2');
var personPrototypeAttribute2Desc = Object.getOwnPropertyDescriptor(lsh,'personPrototypeAttribute2');
// 打印看看
// console.log(sexDesc);
// console.log(ageDesc);
// console.log(animalProtoTypeAttribute2Desc);
// console.log(personPrototypeAttribute2Desc);
// 先修改
sexDesc.enumerable = false;
ageDesc.enumerable = false;
animalProtoTypeAttribute2Desc.enumerable = false;
personPrototypeAttribute2Desc.enumerable = false;
// 使用看看
Object.defineProperty(lsh,'sex',sexDesc);
Object.defineProperty(lsh,'age',ageDesc);
Object.defineProperty(lsh,'animalProtoTypeAttribute2',animalProtoTypeAttribute2Desc);
Object.defineProperty(lsh,'personPrototypeAttribute2',personPrototypeAttribute2Desc);

// look look
console.log(Object.getOwnPropertyNames(lsh));  // [name,age]
console.log(Object.keys(lsh));                 // [name,height]
console.log(Object.values(lsh));               // '我是人','180'
console.log(Object.entries(lsh));              // [['name','我是人'],['height',180]]

for (key in lsh){                              // name,height
    console.log(key);
}
console.log(Reflect.ownKeys(lsh));
// for (value of lsh){                            // '我是人','180'
//     console.log(value);
// }


posted @ 2021-12-11 15:51  睡成蛆  阅读(1800)  评论(0编辑  收藏  举报