Object 对象几种方法的使用

本篇文章稍微会有点长

1. Object.keys();

一种遍历对象并返回对象所有键的简单方法。说白了就是返回对象的key值

let obj = [1,2,3]
let obj1 = {
  name: '张三',
  age: 17,
  level: 4
}
console.log(Object.keys(obj));//["1","2","3"]
console.log(Object.keys(obj1));//["name","age","level"]

2. Object.values();

遍历对象并返回对象的值!说白了就是返回对象的value值

let obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// array like object
let obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']

// array like object with random key ordering
// when we use numeric keys, the value returned in a numerical order according to the keys
let an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']

// getFoo is property which isn't enumerable
let my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
my_obj.foo = 'bar';
console.log(Object.values(my_obj)); // ['bar']

// non-object argument will be coerced to an object
console.log(Object.values('foo')); // ['f', 'o', 'o']

3. Object.entries()

获取一个对象并返回它自己的对象的可枚举字符串键属性 [key, value] 对。

const drinks = {
  maple: "out of stock",
  orang: 3.5
};
 
for(const [name,cost] of Object.entries(drinks)){
console.log(`${name}: ${cost}`)
}

// 打印

”maple: out of stock“
“orang: 3.5”

4. Object.create()

创建一个新对象,使用现有对象作为新创建对象的原型。

let Student =
{
    name:"fuzzy"
display(){
console. log("Name:", this.name);
  }
};

// create object from student prototype
let stdl = Object.create(Student);
stdl.name= "wuzzy";
stdl.display(); 

// 输出
"Name:" "wuzzy"

5.Object.assign( ) ;

将所有可枚举和拥有的属性从源对象复制到目标对象,它返回目标对象,也称为浅拷贝

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

let object3 = {}

const object2 = Object.assign({c: 4, d: 5}, object1);
const object4 = Object.assign(object3, object1);

console.log(object2.c, object2.d);
console.log(object1)  // { a: 1, b: 2, c: 3 }
console.log(object2)  // { c: 3, d: 5, a: 1, b: 2 }
console.log(object4)  // { a: 1, b: 2, c: 3 }

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值