Easiest way to check if string is null or empty

2019-03-08 04:31发布

I've got this code that checks for the empty or null string. It's working in testing.

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

What I'm wondering is if there's a better way than not email? or email is ''. Can I do the equivalent of C# string.IsNullOrEmpty(arg) in CoffeeScript with a single call? I could always define a function for it (like I did) but I'm wondering if there's something in the language that I'm missing.

11条回答
贪生不怕死
2楼-- · 2019-03-08 05:11

Instead of the accepted answer passwordNotEmpty = !!password you can use

passwordNotEmpty = if password then true else false

It gives the same result (the difference only in syntax).

In the first column is a value, in the second is the result of if value:

0 - false
5 - true
'string' - true
'' - false
[1, 2, 3] - true
[] - true
true - true
false - false
null - false
undefined - false
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-08 05:14

It isn't entirely equivalent, but email?.length will only be truthy if email is non-null and has a non-zero .length property. If you not this value the result should behave as you want for both strings and arrays.

If email is null or doesn't have a .length, then email?.length will evaluate to null, which is falsey. If it does have a .length then this value will evaluate to its length, which will be falsey if it's empty.

Your function could be implemented as:

eitherStringEmpty = (email, password) ->
  not (email?.length and password?.length)
查看更多
来,给爷笑一个
4楼-- · 2019-03-08 05:18

Yup:

passwordNotEmpty = not not password

or shorter:

passwordNotEmpty = !!password
查看更多
叛逆
5楼-- · 2019-03-08 05:18

You can use the coffeescript or= operation

s = ''    
s or= null
查看更多
甜甜的少女心
6楼-- · 2019-03-08 05:21

I think the question mark is the easiest way to call a function on a thing if the thing exists.

for example

car = {
  tires: 4,
  color: 'blue' 
}

you want to get the color, but only if the car exists...

coffeescript:

 car?.color

translates to javascript:

if (car != null) {
  car.color;
}

it is called the existential operator http://coffeescript.org/documentation/docs/grammar.html#section-63

查看更多
不美不萌又怎样
7楼-- · 2019-03-08 05:22

This is a case where "truthiness" comes in handy. You don't even need to define a function for that:

test1 = not (email and password)

Why does it work?

'0'       // true
'123abc'  // true
''        // false
null      // false
undefined // false
查看更多
登录 后发表回答