Coffeescript Truthynes咖啡快捷方式
我经常想检查一个变量或属性在CS中是否为null或未定义。除了后缀Coffeescript Truthynes咖啡快捷方式,coffeescript,Coffeescript,我经常想检查一个变量或属性在CS中是否为null或未定义。除了后缀?对于未定义的?@Austin Mullins,是否有一个快捷方式进行“truthy”检查?这是真的,但我假设它对所有内容都进行了检查,并发现CoffeeScript编译器将根据变量的使用产生不同的结果 使用前声明的变量(赋值)检查!=无效的即使未定义的显式赋值(Javascript编译为void 0,返回未定义)也不会改变编译器的行为 结果是一样的吗?看起来工作正常 我发现的演示(预览链接) 按照链接并单击运行按钮(右上角) 代
?
对于未定义的?@Austin Mullins,是否有一个快捷方式进行“truthy”检查?这是真的,但我假设它对所有内容都进行了检查,并发现CoffeeScript编译器将根据变量的使用产生不同的结果
使用前声明的变量(赋值)检查!=无效的即使未定义的显式赋值(Javascript编译为void 0,返回未定义)也不会改变编译器的行为
结果是一样的吗?看起来工作正常
我发现的演示(预览链接)
按照链接并单击运行按钮(右上角)
代码
((arg) ->
str = "Hello World!"
num = 42
foo = arg
# Lets see what the compiler produces
alert "str is #{str}" if str?
alert "num is #{num}" if num?
alert "foo is #{foo}" if foo?
# bar has not been assigned a value or used until now
alert "bar is #{bar}" if bar?
# Lets assign str to something that isn't straight up null
# cs will translate undefined into the expression that returns undefined
str = undefined
# Shorthand
if str?
alert "str? is #{str}"
else
alert "str? is empty"
# Explicit checks
if typeof str isnt "undefined" && str isnt null
alert "str explicit check is #{str}"
else
alert "str explicit check is empty"
).call()
@Austin Mullins,这是真的,但我假设它产生了所有检查,并发现CoffeeScript编译器将根据变量的使用产生不同的结果
使用前声明的变量(赋值)检查!=无效的即使未定义的显式赋值(Javascript编译为void 0,返回未定义)也不会改变编译器的行为
结果是一样的吗?看起来工作正常
我发现的演示(预览链接)
按照链接并单击运行按钮(右上角)
代码
((arg) ->
str = "Hello World!"
num = 42
foo = arg
# Lets see what the compiler produces
alert "str is #{str}" if str?
alert "num is #{num}" if num?
alert "foo is #{foo}" if foo?
# bar has not been assigned a value or used until now
alert "bar is #{bar}" if bar?
# Lets assign str to something that isn't straight up null
# cs will translate undefined into the expression that returns undefined
str = undefined
# Shorthand
if str?
alert "str? is #{str}"
else
alert "str? is empty"
# Explicit checks
if typeof str isnt "undefined" && str isnt null
alert "str explicit check is #{str}"
else
alert "str explicit check is empty"
).call()
根据,?
同时检查这两项。谢谢!作为副本关闭根据,?
检查两者。谢谢!作为dupeIt关闭是有效的,因为=
和==
强制它的操作数<代码>未定义==null//true
和未定义!=空//假
。但是false!=null//true
。这意味着,a!=对于null
或undefined
,null
将为true,但文本false将返回true
。对于未声明的变量来说,这是不同的,因为引用未声明的变量会引发运行时异常,如果您不首先使用typeof
小心处理它,它会起作用,因为=
和==
强制它的操作数<代码>未定义==null//true
和未定义!=空//假
。但是false!=null//true
。这意味着,a!=对于null
或undefined
,null
将为true,但文本false将返回true
。而对于未声明的变量则不同,因为如果不首先使用typeof
小心处理,引用未声明的变量会引发运行时异常。