Object.keys(obj)
返回一個由給定對象的所有自身屬性的鍵組成的數(shù)組艇挨。
let obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj)); // 輸出: ["a", "b", "c"]
Object.values(obj)
返回一個由給定對象自身的所有可枚舉屬性值的數(shù)組凝垛。
let obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj)); // 輸出: [1, 2, 3]
Object.entries(obj)
返回一個給定對象自身可枚舉屬性的鍵值對數(shù)組。
let obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj)); // 輸出: [["a", 1], ["b", 2], ["c", 3]]
Object.assign(target, ...sources)
將所有可枚舉屬性的值從一個或多個源對象復制到目標對象帖烘。它將返回目標對象洒试。
let target = { a: 1, b: 2 };
let source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target); // 輸出: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget); // 輸出: Object { a: 1, b: 4, c: 5 }
Object.create(proto, [propertiesObject])
創(chuàng)建一個新對象缀棍,使用現(xiàn)有的對象來提供新創(chuàng)建的對象的proto
const person = {
isHuman: false,
printIntroduction: function() {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
const me = Object.create(person);
me.name = "Matthew"; // "name" 是 "me" 的屬性.
me.isHuman = true; // 繼承的屬性 "isHuman" 被 "me" 覆蓋了.
me.printIntroduction();
// 輸出: "My name is Matthew. Am I human? true"
Object.hasOwnProperty(obj, prop)
檢查一個對象是否擁有某個屬性,不考慮該對象的原型鏈秦踪。
let obj = { prop: 'exists' };
console.log(Object.hasOwnProperty.call(obj, 'prop')); // 輸出: true
console.log(Object.hasOwnProperty.call(obj, 'toString')); // 輸出: false
Object.freeze(obj)
凍結(jié)一個對象褐捻,這意味著你不能向這個對象添加新的屬性,不能刪除現(xiàn)有屬性洋侨,不能修改屬性的可枚舉性舍扰、可配置性、可寫性希坚,以及屬性的值边苹。
let obj = { prop: 42 };
Object.freeze(obj);
obj.prop = 33;
console.log(obj.prop); // 輸出: 42
obj.newProp = "It's new";
console.log(obj.newProp); // 輸出: undefined