Is there a standard function to check for null, un

2018-12-31 04:11发布

Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

30条回答
柔情千种
2楼-- · 2018-12-31 04:50

It may be usefull.

[null, undefined, ''].indexOf(document.DocumentNumberLabel) > -1
查看更多
心情的温度
3楼-- · 2018-12-31 04:51

you can use:

If clause to validate if the string or value is not empty. like this:

if (someVar.value) 
{
  //its not emppty
}
else
{
  //Its empty
}
查看更多
一个人的天荒地老
4楼-- · 2018-12-31 04:52

You can just check if the variable has a truthy value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== 'undefined' ) {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html

查看更多
萌妹纸的霸气范
5楼-- · 2018-12-31 04:52

! check for empty strings (""), null, undefined, false and the number 0 and NaN. Say, if a string is empty var name = "" then console.log(!name) returns true.

function isEmpty(val){
  return !val;
}

this function will return true if val is empty, null, undefined, false, the number 0 or NaN.

查看更多
旧时光的记忆
6楼-- · 2018-12-31 04:53

If you are using TypeScript and don't want to account for "values those are false" then this is the solution for you:

First: import { isNullOrUndefined } from 'util';

Then: isNullOrUndefined(this.yourVariableName)

Please Note: As mentioned below this is now deprecated, use value === undefined || value === null instead. ref.

查看更多
伤终究还是伤i
7楼-- · 2018-12-31 04:53

This function check for empty object {},empty array [], null, undefined and blank string ""

function isEmpty(val) {
  //check for empty object {}, array []
  if (val !== null && typeof val === 'object') {
    if (Object.keys(obj).length === 0) {
      return true;
    }
  }
  //check for undefined, null and "" 
  else if (val == null || val === "") {
    return true;
  }
  return false;
}

var val={};
isEmpty(val) -> true
val=[];
isEmpty(val) -> true
isEmpty(undefined) -> true
isEmpty(null) -> true
isEmpty("") -> true
isEmpty(false) -> false
isEmpty(0) -> false

查看更多
登录 后发表回答