1、Object.keys()
一种遍历对象并返回对象所有键的简单方法。
const obj = {name: 'xx', age: 18, level: 4}
console.log(Object.keys(obj));
// 输出:
['name', 'age', 'level']
2、Object.values()
遍历对象并返回对象的值!
const obj = {name: 'xx', age: 18, level: 4}
console.log(Object.keys(obj));
// 输出:
['xx', 18, 4]
3、Object.entries()
获取一个对象并返回它自己的对象的可枚举字符串键属性 [key, value] 对
const drinks = {
maple: 'out of stock',
orange: 3.5
}
for(const [name, cost] of Object.entries(drinks)){
console.log('${name}: ${cost}');
}
// 输出:
'maple: out of stock'
'orange: 3.5'
4、Object.create()
创建一个新对象,使用现有对象作为新创建对象的原型。
let Student = {
name: 'fuzzy',
display() {
console.log('Name:', this.name);
}
}
let std1 = Object.create(Student);
std1.name = 'wwz'
std1.display();
// 输出:
'Name:' 'wwz'
5、Object.assign()
将所有可枚举和拥有的属性从源对象复制到目标对象,它返回目标对象,也称为浅拷贝。
const target = {a: 1, b: 2};
const source = {b: 4, c: 5};
const returnedTarget = Object.assign(target, source);
console.log(target);
console.log(returnedTarget);
// 输出
{
'a': 1,
'b': 4,
'c': 5
}
6、Object.seal()
密封一个防止新属性添加到它的对象,并将所有现有属性标记为不可配置。
const car = {
price: 15000
};
Object.seal(car);
car.price = 18000;
console.log(car.price);
// 18000
// value changed successfully
delete car.price;
console.log(car.price);
// 18000
// cannot delete when sealed
7、Object.freeze()
冻结对象,无法再更改冻结的对象;
- 新属性被添加到对象。
- 要从对象中删除的现有属性。
- 更改现有属性的可枚举性、可配置性或可写性。
- 更改现有对象属性和原型的值。
const client = {
bdget: 3000
}
Object.freeze(client);
client.budget = 2500;
// Shows error in strict mode
console.log(client.budget);
// 3000
// unchanged value as output