本文目录
- Object.keys()
- Object.values()
- Object.entries()
- Object.create()
- Object.assign()
- 6.Object.seal()
- Object.freeze()
- 8.Object.hasOwnProperty()
1. Object.keys()
一种遍历对象并返回对象所有键的简单方法。
const employee = { name: 'Daniel', age: 40, occupation: 'Engineer', level: 4 };
console.log(Object.keys(employee))
输出
["name","age","occupation","level"]
Tips:JS 中 Object 的 keys 是无序的吗?
1.在 ES6 之前 Object 的键值对是无序的;
2.在 ES6 之后 Object 的键值对按照自然数、非自然数和 Symbol 进行排序,自然数是按照大小升序进行排序,其他两种都是按照插入的时间顺序进行排序。
2. Object.values()
遍历对象并返回对象的值
const employee = { name: 'Daniel', age: 40, occupation: 'Engineer', level: 4 };
console.log(Object.values(employee))
输出
["Daniel",40,"Engineer",4]
3. Object.entries()
获取一个对象并返回它自己的对象的可枚举字符串键属性 [key, value] 对。
const employee = { name: 'Daniel', age: 40, occupation: 'Engineer', level: 4 };
console.log(Object.entries(employee))
输出
[["name","Daniel"], ["age",40],[ "occupation","Engineer"], ["level",4]]
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 );
};
// create object from student prototype
let std1 = 0bject.create(Student);
stdl.name = "wuzzy";
stdl.display();
输出
"Name:wuzzy”
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": 2,
"c": 3,
}
//target和returnedTarget指向的存储地址是同一个
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
8.Object.hasOwnProperty()
Object的hasOwnProperty()方法返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。
判断自身属性是否存在
var o = new Object();
o.prop = 'exists';
function changeO() {
o.newprop = o.prop;
delete o.prop;
}
o.hasOwnProperty('prop'); // true
changeO();
o.hasOwnProperty('prop'); // false
判断自身属性与继承属性
function foo() {
this.name = 'foo'
this.sayHi = function () {
console.log('Say Hi')
}
}
foo.prototype.sayGoodBy = function () {
console.log('Say Good By')
}
let myPro = new foo()
console.log(myPro.hasOwnProperty('name')) // true
console.log(myPro.hasOwnProperty('toString')) // false
console.log(myPro.hasOwnProperty('sayHi')) // true
console.log(myPro.hasOwnProperty('sayGoodBy')) // false
console.log('sayGoodBy' in myPro) // true