【发布时间】:2012-04-16 22:06:45
【问题描述】:
我想使用 CoffeeScript 存在运算符来检查某些对象属性是否未定义。但是,我遇到了一个小问题。
这样的代码:
console.log test if test?
编译为:
if (typeof test !== "undefined" && test !== null) console.log(test);
这是我希望看到的行为。但是,当我尝试对对象属性使用它时,如下所示:
console.log test.test if test.test?
我得到了类似的东西:
if (test.test != null) console.log(test.test);
这看起来根本不像是对 undefined 的检查。我可以实现与将其用于对象相同的 (1:1) 行为的唯一方法是使用更大的检查:
console.log test.test if typeof test.test != "undefined" and test.test != null
问题是 - 我做错了什么吗?或者编译后的代码是否足以检查属性的存在(带有类型转换的空检查)?
【问题讨论】:
-
@Bergi,这个问题是四年前提出的,另一个是两年前。另一个不是重复的吗? :)
-
对,我只是觉得另一个人的答案更好。我想他们应该合并。
标签: coffeescript existential-operator