简体   繁体   English

测试是否定义了变量,如果没有定义,请在Coffeescript中为它分配一个空字符串?

[英]Test if a variable is defined, if not, assign it an empty string in Coffeescript?

Here is my coffeescript code: 这是我的coffeescript代码:

if c.urls.voice then c.urls.voice else ""

Does anyone have any ideas about whether there is a better way to write this code in Coffeescript? 是否有人对在Coffeescript中编写此代码是否有更好的方法有任何想法?

Just use the existential operator to assign to a non-existing variable/property: 只需使用存在运算符将其分配给不存在的变量/属性即可:

c.urls.voice ?= ""

Alternatively, if you don't want to assign it but only access with a default value, use the or (or || ) operator: 另外,如果您不想分配它,而只希望使用默认值进行访问,请使用or (或|| )运算符:

… = c.urls.voice or "" // equivalent to your if statement

however I guess you're even here actually looking for the existential operator which specifically checks for null and undefined values, not all falsy ones: 但是我想你甚至在这里实际上是在寻找存在运算符,该运算符专门检查nullundefined值,而不是所有虚假的值:

… = c.urls.voice ? ""

I found this works for me: 我发现这对我有用:

c.urls.voice ? ""

which will compiles into: 将编译为:

var _ref;

if ((_ref = c.urls.voice) != null) {
  _ref;
} else {
  "";
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM