如何使用 CoffeeScript 存在运算符检查某些对象属性是否未定义? [英] How do I use the CoffeeScript existential operator to check some object properties for undefined?

查看:19
本文介绍了如何使用 CoffeeScript 存在运算符检查某些对象属性是否未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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

其他时候它只是编译成

x != null

两者是等价的, 因为当 xx != null 将是 false>nullundefined.所以 x != null 是表达 (x !== undefined && x !== null) 的更简洁的方式.typeof 编译发生的原因是编译器认为 x 可能根本没有定义,在这种情况下进行相等性测试会触发 ReferenceError: x is未定义.

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,但您无法通过引用现有对象的未定义属性,因此编译器选择较短的输出.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆