如何使用CoffeeScript存在操作符来检查某些对象属性是否未定义? [英] How do I use the CoffeeScript existential operator to check some object properties for undefined?
问题描述
我想使用CoffeeScript存在操作符来检查一些对象属性是否未定义。但是,我遇到了一些问题。
I would like to use the CoffeeScript existential operator to check some object properties for undefined. However, I encountered a little problem.
这样的代码:
console.log test if test?
编译为:
if (typeof test !== "undefined" && test !== null) console.log(test);
这是我想看到的行为。但是,当我尝试使用它对象属性,像这样:
Which is the behavior I would like to see. However, when I try using it against object properties, like this:
console.log test.test if test.test?
我得到类似的结果:
if (test.test != null) console.log(test.test);
这看起来不像是对undefined的检查。我可以通过使用一个更大的检查达到相同(1:1)行为的对象是唯一的方法:
Which desn't look like a check against undefined at all. The only way I could have achieved the same (1:1) behavior as using it for objects was by using a larger check:
console.log test.test if typeof test.test != "undefined" and test.test != null
问题是 - 我做错了什么?或者是编译的代码什么足以检查属性的存在(一个空检查类型转换)?
The question is - am I doing something wrong? Or is the compiled code what is enough to check for existence of a property (a null check with type conversion)?
推荐答案
是与存在操作符的常见混淆点:有时
This is a common point of confusion with the existential operator: Sometimes
x?
编译为
typeof test !== "undefined" && test !== null
而其他时候它只是编译到
and other times it just compiles to
x != null
>这两个是等效的,因为 x!= null
将会是 false
> x 是 null
或 undefined
。因此 x!= null
是一种更紧凑的表达方法(x!== undefined&& x!== null)
。发生 typeof
编译的原因是编译器认为 x
可能根本没有定义,在这种情况下一个等式测试将触发 ReferenceError:x未定义
。
The two are equivalent, because x != null
will be false
when x
is either null
or undefined
. So x != null
is a more compact way of expressing (x !== undefined && x !== null)
. The reason the typeof
compilation occurs is that the compiler thinks x
may not have been defined at all, in which case doing an equality test would trigger ReferenceError: x is not defined
.
在您的特定情况下, test.test
可能有 undefined
的值,但是你不能得到 ReferenceError
通过引用现有对象上的未定义属性,因此编译器选择较短的输出。
In your particular case, test.test
may have the value undefined
, but you can't get a ReferenceError
by referring to an undefined property on an existing object, so the compiler opts for the shorter output.
这篇关于如何使用CoffeeScript存在操作符来检查某些对象属性是否未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!