ES8对对象的扩展

小编不知道大家的五一节过的怎么样,反正对于小编来说,收获还是有一些的,今天小编继续更新js中关于对象的一些新特性,期待着和大家一起进步。大家还可以关注我的微信公众号,蜗牛全栈。

一、Object.values():获取对象内值的数组

const obj = {
    name:"lilei",
    web:"www.baidu.com",
    course:"math"
}
console.log(Object.values(obj)) // ["lilei","www.baidu.com","math"]

二、Object.entries():返回二位数组,每个数组包含key和value

const obj = {
    name:"lilei",
    web:"www.baidu.com",
    course:"math"
}
console.log(Object.entries(obj))  // [["name","lilei"],["web","www.baidu.com"],["course","math"]]
console.log(Object.entries(["a","b","c"])) // [["0","a"],["1","b"],["2","c"]]

三、循环遍历:与es6中的解构和字符串模板结合

const obj = {
    name:"lilei",
    web:"www.baidu.com",
    course:"math"
}
for(let [key,val] of Object.entries(obj)){
    console.log(`${key}:${val}`)  // name:lilei   web:www.baidu.com   course:math
}

四、es8之前语法

const obj = {
    name:"lilei",
    web:"www.baidu.com",
    course:"math"
}
console.log(Object.keys(obj)) // ["name","web","course"]
const res = Object.keys(obj).map(key => obj[key])
console.log(res) // ["lilei","www.baidu.com","math"]

五、Object.getOwnPropertyDescriptors():获取对象自身属性修饰符

const obj = {
    name:"lilei",
    course:"math"
}
const desc = Object.getOwnPropertyDescriptors(obj)
console.log(desc) 
// {
//     name:{
//         value:"lilei", // 默认值
//         writable:true, // 属性是否可以改
//         enumerable:true,  // 是否可以通过for...in 循环遍历
//         configurable:true  // 是否可以通过delete删除掉
//     },
//     course:{
//         value:"math",
//         writable:true,
//         enumerable:true,
//         configurable:true
//     }
// }

六、与Reflect联合使用

const obj= {}
Reflect.defineProperty(obj,'name',{
    value:"lilei",
    writable:false,
    configurable:false,
    enumerable:true
})
Reflect.defineProperty(obj,'age',{
    value:18,
    writable:false,
    configurable:false,
    enumerable:false
})
console.log(obj) // {name:"lilei"}
obj.name= "zhangsan"
console.log(obj) // {name:"lilei"}
delete obj.name
console.log(obj) // {name:"lilei"}
for(let key in obj){
    console.log(key)  // 只有name。没有age
}

七、Object.getOwnPropertyDescriptor()

const obj = {
    name:"lilei",
    course:"math"
}
const desc = Object.getOwnPropertyDescriptor(obj,"name")
console.log(desc)
// {
//     value:"lilei", // 默认值
//     writable:true, // 属性是否可以改
//     enumerable:true,  // 是否可以通过for...in 循环遍历
//     configurable:true  // 是否可以通过delete删除掉
// }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鹰3995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值