简体   繁体   中英

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" ?

Just add typeof operator, like this:

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. The comparison that CoffeeScript generates for 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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