乐趣区

关于javascript: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 删除掉
// }
退出移动版