使用未定义作为属性键是否保证结果将是未定义?

huangapple go评论85阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年8月4日 22:14:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定