a {}-6ren">
gpt4 book ai didi

javascript - 如何判断某个符号是否被用作 key ?

转载 作者:行者123 更新时间:2023-11-28 15:10:44 25 4
gpt4 key购买 nike

我正在探索 ES6 符号,试图理解它们是什么,但我无法理解这种行为

> let sym = Symbol()
> let a = {}
> a[sym]= "value"
'value'
> a
{}
> Object.keys(a)
[]
> Object.getOwnPropertyNames(a)
[]
> a[sym]
'value'
> a[Symbol()]
undefined
> JSON.stringify(sym)
undefined
> JSON.stringify(a)
'{}'
> sym
Symbol()

我还不懂符号,但是键和值隐藏在哪里?!? java脚本是否落入巫术领域?无论如何,有什么办法可以告诉它它的存在吗?

编辑::

感谢您通知我有关 Object.getOwnPropertySymbols(); 的信息

所以在 ES6 中我必须检查 Object.getOwnPropertyNames() 和 Object.getOwnPropertySymbols() 是否有隐藏的不可枚举属性?

最佳答案

来自MDN看起来您可以使用 Object.getOwnPropertySymbols(a) 获取它们。

我偶然发现这篇文章,它提供了一些额外的背景信息: http://blog.keithcirkel.co.uk/metaprogramming-in-es6-symbols/

Symbols give a whole new sense of purpose to Objects - they provide a kind of hidden under layer to Objects - not iterable over, not fetched using the already existing Reflection tools and guaranteed not to conflict with other properties in the object!

关于javascript - 如何判断某个符号是否被用作 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36583010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com