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:23

If you need to check that the content is a string, not null and not an array, use a simple typeof comparison:

 if typeof email isnt "string"
查看更多
Anthone
3楼-- · 2019-03-08 05:30

Here is a jsfiddle demonstrating a very easy way of doing this.

Basicly you simply do this is javascript:

var email="oranste";
var password="i";

if(!(email && password)){
    alert("One or both not set");        
}
else{
    alert("Both set");   
}

In coffescript:

email = "oranste"
password = "i"
unless email and password
  alert "One or both not set"
else
  alert "Both set"

Hope this helps someone :)

查看更多
放荡不羁爱自由
4楼-- · 2019-03-08 05:35
unless email? and email
  console.log 'email is undefined, null or ""'

First check if email is not undefined and not null with the existential operator, then if you know it exists the and email part will only return false if the email string is empty.

查看更多
混吃等死
5楼-- · 2019-03-08 05:35

Based on this answer about checking if a variable has a truthy value or not , you just need one line:

result = !email or !password

& you can try it for yourself on this online Coffeescript console

查看更多
三岁会撩人
6楼-- · 2019-03-08 05:35

I'm pretty sure @thejh 's answer was good enough to check empty string BUT, I think we frequently need to check that 'Does it exist?' and then we need to check 'Is it empty? include string, array and object'

This is the shorten way for CoffeeScript to do this.

tmp? and !!tmp and !!Object.keys(tmp).length

If we keep this question order, that would be checked by this order 1. does it exist? 2. not empty string? 3. not empty object?

so there wasn't any problems for all variable even in the case of not existed.

查看更多
登录 后发表回答