對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);
// }



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM