Easiest way to check if string is null or empty

前端 未结 11 1170
南笙
南笙 2021-01-30 12:30

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          


        
相关标签:
11条回答
  • 2021-01-30 12:42

    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
    
    0 讨论(0)
  • 2021-01-30 12:44

    You can use the coffeescript or= operation

    s = ''    
    s or= null
    
    0 讨论(0)
  • 2021-01-30 12:46

    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

    0 讨论(0)
  • 2021-01-30 12:50

    Yup:

    passwordNotEmpty = not not password
    

    or shorter:

    passwordNotEmpty = !!password
    
    0 讨论(0)
  • 2021-01-30 12:52
    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.

    0 讨论(0)
  • 2021-01-30 12:54

    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

    0 讨论(0)
提交回复
热议问题