You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:24:16