其他分享
首页 > 其他分享> > ES8对对象的扩展

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删除掉
// }

 

标签:lilei,obj,name,对象,Object,扩展,ES8,console,log
来源: https://www.cnblogs.com/feiying3995/p/14943482.html