简体   繁体   English

Coffeescript和变量检查

[英]Coffeescript and variable check

I have the following code: 我有以下代码:

if variablename?
   alert "YES!"

l = []

if l[3]?
  alert "YES!"

It's translated into this: 它被翻译成:

var l;

if (typeof variablename !== "undefined" && variablename !== null) {
  alert("YESSS!");
}

l = [];

if (l[3] != null) {
  alert("YESSS!");
}

In Coffeescript, how would I express l[3] !== "undefined" ? 在Coffeescript中,我将如何表达l[3] !== "undefined"

Just add typeof operator, like this: 只需添加typeof运算符,如下所示:

if typeof l[3] != 'undefined'
  alert 'Yes!'

Beware that l[3] !== "undefined" is asking whether l[3] is different from the string that says "undefined", not if its value isn't undefined. 请注意l[3] !== "undefined"询问l[3]是否与显示“undefined”的字符串不同,而不是它的值是否未定义。 The comparison that CoffeeScript generates for l[3]? CoffeeScript为l[3]?生成的比较l[3]? -> l[3] != null will verify when l[3] is some value different from undefined or null, which is what you want to ask most of the time :) - > l[3] != null将验证l[3]是什么时候某个值与undefined或null不同,这是你想要问的大部分时间:)

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

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