检查字符串是空还是空的最简单方法

jco*_*lum 86 coffeescript

我有这个代码检查空字符串或空字符串.它正在测试中.

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)

  • 它对于包含所有空格的字符串都失败了...因此不适用于空白 (3认同)
  • 因为我的可读性而太"聪明"了; 不要以为我会用它,但是好工作 (2认同)

小智 37

它不是完全等价的,但email?.length如果email是非null并且具有非零.length属性,则只会是真实的.如果您使用not此值,则结果应该按字符串和数组的方式运行.

如果emailnull或没有.length,那么email?.length将评估null,这是假的.如果它确实有一个.length那么这个值将评估它的长度,如果它是空的,它将是假的.

您的功能可以实现为:

eitherStringEmpty = (email, password) ->
  not (email?.length and password?.length)
Run Code Online (Sandbox Code Playgroud)

  • 数组有.length (2认同)

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)


cut*_*ine 5

unless email? and email
  console.log 'email is undefined, null or ""'
Run Code Online (Sandbox Code Playgroud)

首先使用存在运算符检查电子邮件是否未定义且不为空,然后如果您知道它存在,则该and email部分只会在电子邮件字符串为空时返回 false。