我有这个代码检查空字符串或空字符串.它正在测试中.
eitherStringEmpty= (email, password) ->
emailEmpty = not email? or email is ''
passwordEmpty = not password? or password is ''
eitherEmpty = emailEmpty || passwordEmpty
test1 = eitherStringEmpty "A", "B" # expect false
test2 = eitherStringEmpty "", "b" # expect true
test3 = eitherStringEmpty "", "" # expect true
alert "test1: #{test1} test2: #{test2} test3: #{test3}"
Run Code Online (Sandbox Code Playgroud)
我想知道的是,还有更好的方法not email? or email is ''.我可以通过string.IsNullOrEmpty(arg)一次调用在CoffeeScript中完成相当于C#的操作吗?我总是可以为它定义一个函数(就像我一样),但我想知道是否有一些我缺少的语言.
the*_*ejh 116
对:
passwordNotEmpty = not not password
Run Code Online (Sandbox Code Playgroud)
或更短:
passwordNotEmpty = !!password
Run Code Online (Sandbox Code Playgroud)
小智 37
它不是完全等价的,但email?.length如果email是非null并且具有非零.length属性,则只会是真实的.如果您使用not此值,则结果应该按字符串和数组的方式运行.
如果email是null或没有.length,那么email?.length将评估null,这是假的.如果它确实有一个.length那么这个值将评估它的长度,如果它是空的,它将是假的.
您的功能可以实现为:
eitherStringEmpty = (email, password) ->
not (email?.length and password?.length)
Run Code Online (Sandbox Code Playgroud)
Ric*_*asi 14
这是"真实性"派上用场的情况.您甚至不需要为此定义函数:
test1 = not (email and password)
Run Code Online (Sandbox Code Playgroud)
它为什么有效?
'0' // true
'123abc' // true
'' // false
null // false
undefined // false
Run Code Online (Sandbox Code Playgroud)
unless email? and email
console.log 'email is undefined, null or ""'
Run Code Online (Sandbox Code Playgroud)
首先使用存在运算符检查电子邮件是否未定义且不为空,然后如果您知道它存在,则该and email部分只会在电子邮件字符串为空时返回 false。