英文:
Does using undefined as a property key guarantee the result will be undefined?
问题
在通过变量检索对象属性的情况下,例如:
myObject[someField]
存在 someField
(它是一个字符串)可能为 undefined
(可能是未初始化的字符串值的结果)的可能性。我的实验表明,对于我能想到的所有类型的对象,结果都是 undefined
,即:
anyObject[undefined] === undefined
这是一个众所周知的行为吗?我可以依赖这个吗?在相关文档中似乎找不到相关信息,我的备选方案是重写上述代码为:
someField ? myObject[someField] : undefined;
但如果能保证在尝试访问属性 undefined
时始终返回 undefined
,我真的更喜欢简洁的方式。
英文:
In a situation where an object property is retrieved through a variable i.e.:
myObject[someField]
there is the possibility of someField
(which is a string) to be undefined
(the result of a potentially uninitialized string value). My experiments show that for all types of objects I can think of the result is undefined
i.e.:
anyObject[undefined] === undefined
Is this a well known behavior, something I can rely on? Can't seem to find something in related documentation and my alternative would be to re-write the above as
someField ? myObject[someField] : undefined;
but would really prefer the succinct way if there is a guarantee that undefined
is returned whenever we try to access the property undefined
.
答案1
得分: 3
No, accessing obj[undefined]
will not always return undefined
. Like any value used as property name, undefined
will get coerced to a string (unless it is a symbol), so it will actually access a property named "undefined". obj[undefined]
is equivalent to obj["undefined"]
or obj.undefined
. It will return the property value if such a property exists, e.g. when obj = {undefined: true};
.
You should indeed write
someField != null ? myObject[someField] : undefined;
if someField: undefined | string
.
英文:
No, accessing obj[undefined]
will not always return undefined
. Like any value used as property name, undefined
will get coerced to a string (unless it is a symbol), so it will actually access a property named "undefined". obj[undefined]
is equivalent to obj["undefined"]
or obj.undefined
. It will return the property value if such a property exists, e.g. when obj = {undefined: true};
.
You should indeed write
someField != null ? myObject[someField] : undefined;
if someField: undefined | string
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论