JavaScript中Object.defineProperty()的console.log异常表现问题
为什么
console.log(profile)不显示Object.defineProperty()添加的age属性? 嘿,这个问题我之前也踩过坑,其实是Object.defineProperty()的默认配置在搞鬼!
问题根源
当你用Object.defineProperty()给对象新增属性时,默认情况下这个属性是不可枚举(non-enumerable)的。而console.log()在打印对象时,只会输出那些enumerable为true的属性。这就刚好对应你遇到的现象:
- 直接
console.log(profile)只显示name——因为它是对象初始化时自带的可枚举属性 - 你能正常访问
profile.age,也能在调试器里看到它——调试器会展示对象的所有属性,不管是否可枚举
解决方案
只需要在定义age属性时,显式把enumerable设为true就行:
let profile = { name: 'Barry Allen' } // 显式添加enumerable配置项 Object.defineProperty(profile, 'age', { value: 23, writable: true, enumerable: true }) console.log(profile) // 现在会输出 {name: "Barry Allen", age: 23} console.log(profile.age) // 23
这样修改后,age属性就会被console.log()枚举并显示出来,完全符合你的预期啦~
内容的提问来源于stack exchange,提问作者Ravi Waghmare
相关产品推荐
相关产品推荐

