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

You can directly use the equality operator

<script>
    var firstName;
    var lastName = null;
    /* Since null == undefined is true, the following statements will catch both null and undefined */
        if(firstName == null){
            alert('Variable "firstName" is undefined.');
        }    
        if(lastName == null){
           alert('Variable "lastName" is null.');
        }
</script>

demo @ How to determine if variable is undefined or null using JavaScript

查看更多
心情的温度
3楼-- · 2018-12-31 05:00

If you prefer plain javascript try this:

  /**
   * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
   * length of `0` and objects with no own enumerable properties are considered
   * "empty".
   *
   * @static
   * @memberOf _
   * @category Objects
   * @param {Array|Object|string} value The value to inspect.
   * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
   * @example
   *
   * _.isEmpty([1, 2, 3]);
   * // => false
   *
   * _.isEmpty([]);
   * // => true
   *
   * _.isEmpty({});
   * // => true
   *
   * _.isEmpty('');
   * // => true
   */

function isEmpty(value) {
    if (!value) {
      return true;
    }
    if (isArray(value) || isString(value)) {
      return !value.length;
    }
    for (var key in value) {
      if (hasOwnProperty.call(value, key)) {
        return false;
      }
    }
    return true;
  }

Otherwise, if you are already using underscore or lodash, try:

_.isEmpty(value)
查看更多
长期被迫恋爱
4楼-- · 2018-12-31 05:01

I know this is an old question, but this is the safest check and I haven't seen it posted here exactly like that:

if (typeof value != 'undefined' && value) {
    //deal with value'
};

It will cover cases where value was never defined, and also any of these:

  • null
  • undefined (value of undefined is not the same as a parameter that was never defined)
  • 0
  • "" (empty string)
  • false
  • NaN

P.S. no need for strict equality in typeof value != 'undefined'

查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 05:02

Although an oldie, what forget is that they should wrap their code block and then catch the error and then test...

function checkup( t ){
  try{
    for(p in t){
      if( p.hasOwnProperty( t ) ){
        return true;
      }
    }
    return false;
  }catch(e){
    console.log("ERROR : "+e);
    return e;
  }
}

So you really don't have to check for a potential problem before hand, you simply catch it and then deal with it how you want.

查看更多
荒废的爱情
6楼-- · 2018-12-31 05:03

The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:

if (typeof(value) !== "undefined" && value)

or

if (typeof value  !== "undefined" && value)
查看更多
柔情千种
7楼-- · 2018-12-31 05:03

You are a bit overdoing it. To check if a variable is not given a value, you would only need to check against undefined and null.

function isEmpty(value){
    return (typeof value === "undefined" || value === null);
}

This is assuming 0, "", and objects(even empty object and array) are valid "values".

查看更多
登录 后发表回答