是否有一个标准函数来检查JavaScript中的null、未定义或空白变量?

是否有一个标准函数来检查JavaScript中的null、未定义或空白变量?,javascript,null,comparison,undefined,Javascript,Null,Comparison,Undefined,是否有一个通用JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况: function isEmpty(val){ return (val === undefined || val == null || val.length <= 0) ? true : false; } 函数为空(val){ return(val==undefined | | val==null | | val.length您只需检查变量是否具有tr

是否有一个通用JavaScript函数来检查变量是否有值,并确保它不是
未定义的
空的
?我有这个代码,但我不确定它是否涵盖所有情况:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}
函数为空(val){
return(val==undefined | | val==null | | val.length您只需检查变量是否具有
truthy
值。这意味着

if( value ) {
}
如果
,则将计算为

  • 空的
  • 未定义
  • 空字符串(“”)
  • 0
  • 假的
上面的列表表示ECMA-/Javascript中所有可能的
falsy
值。请在
ToBoolean
部分找到它

此外,如果您不知道变量是否存在(也就是说,如果声明了变量),则应使用
typeof
运算符进行检查

if( typeof foo !== 'undefined' ) {
    // foo could get resolved and it's defined
}
如果您可以确保至少声明了一个变量,那么应该直接检查它是否有如上所示的
truthy

function isEmpty(value){
  return (value == null || value.length === 0);
}
这将在以下情况下返回真值:

undefined  // Because undefined == null

null

[]

""
零参数函数,因为函数的
长度
是它所使用的声明参数的数量

要禁止后一个类别,您可能只需要检查空白字符串

function isEmpty(value){
  return (value == null || value === '');
}

检查值是否未定义或为null的详细方法为:

return value === undefined || value === null;
您也可以使用
==
运算符,但这需要:


你做得有点过头了。要检查一个变量是否没有给定值,你只需要检查undefined和null

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

这是假设
0
,以及对象(即使是空对象和数组)都是有效的“值”。

如果变量尚未声明,您将无法使用函数测试是否未定义,因为您将得到一个错误

if (foo) {}
function (bar) {}(foo)
如果未声明foo,则两者都将生成错误

如果要测试是否已声明变量,可以使用

typeof foo != "undefined"
if (typeof foo != "undefined" && foo) {
    //code here
}
如果您想测试是否已经声明了foo,并且它有一个可以使用的值

typeof foo != "undefined"
if (typeof foo != "undefined" && foo) {
    //code here
}

这是最安全的支票,我还没有看到它像这样贴在这里:

if (typeof value !== 'undefined' && value) {
    //deal with value'
};
它将涵盖从未定义值的情况,以及以下任何情况:

  • 空的
  • 未定义(未定义的值与从未定义的参数不同)
  • 0
  • “”(空字符串)
  • 假的

编辑:更改为严格相等(!==),因为它现在是标准;)

这是我的-如果值为null、未定义等或空白(即仅包含空格),则返回true:


第一个具有最佳评级的答案是错误的。如果值未定义,它将在现代浏览器中引发异常。您必须使用:

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


检查空字符串(“”)、null、未定义、false以及数字0和NaN。说,如果字符串为空
var name=“”
,则
console.log(!name)
返回
true

function isEmpty(val){
  return !val;
}
如果val空、null、未定义、false、数字0或NaN,则此函数将返回true


根据您的问题域,您可以像
!val
!!val

一样使用以下功能:

function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
或在ES7中(如果需要进一步改进,请发表意见)

结果:

typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
“请注意,绑定运算符(::)根本不是ES2016(ES7)的一部分,也不是ECMAScript标准的任何更高版本。它目前是引入该语言的第0阶段(strawman)建议。”–Simon Kjellberg。作者希望补充他对接受皇家提升的美丽提议的支持。

此条件检查

if (!!foo) {
    //foo is defined
}

是您所需要的一切。

如果您喜欢纯javascript,请尝试以下方法:

  /**
   * 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;
  }
否则,如果您已经在使用下划线或lodash,请尝试:

_.isEmpty(value)
检查默认值的步骤

检查结果:

isVariableHaveDefaltVal(' '); // string          
isVariableHaveDefaltVal(false); // boolean       
var a;           
isVariableHaveDefaltVal(a);               
isVariableHaveDefaltVal(0); // number             
isVariableHaveDefaltVal(parseInt('')); // NAN isNAN(' '); - true         
isVariableHaveDefaltVal(null);              
isVariableHaveDefaltVal([]);               
isVariableHaveDefaltVal(/ /);              
isVariableHaveDefaltVal(new Object(''));               
isVariableHaveDefaltVal(new Object(false));            
isVariableHaveDefaltVal(new Object(0)); 
typeOfVar( function() {} );
我使用@Vix function()检查哪种类型的对象

使用instansof«

var prototypes_or_Literals = function (obj) {
    switch (typeof(obj)) {
        // object prototypes
        case 'object':
            if (obj instanceof Array)
                return '[object Array]';
            else if (obj instanceof Date)
                return '[object Date]';
            else if (obj instanceof RegExp)
                return '[object regexp]';
            else if (obj instanceof String)
                return '[object String]';
            else if (obj instanceof Number)
                return '[object Number]';

            else
                return 'object';
        // object literals
        default:
            return typeof(obj);
    }   
};
output test «
prototypes_or_Literals( '' ) // "string"
prototypes_or_Literals( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"        

这将检查不确定嵌套的变量是否未定义

function Undef(str) 
{
  var ary = str.split('.');
  var w = window;
  for (i in ary) {
    try      { if (typeof(w = w[ary[i]]) === "undefined") return true; }
    catch(e) { return true; }
  }
  return false;
}

if (!Undef("google.translate.TranslateElement")) {
以上检查Google translate函数TranslateElement是否存在。这相当于:

if (!(typeof google === "undefined" 
 || typeof google.translate === "undefined" 
 || typeof google.translate.TranslateElement === "undefined")) {
但该解决方案设计过度,如果您不想在以后根据业务模型的需要修改该功能,那么直接在代码中使用它会更简洁:

if(!val)...

这永远不会引发错误。如果myObject、child或myValue为null,则myNewValue将为null。不会引发任何错误。对于所有因类似问题而来到这里的人,以下内容非常有用,我的库中已保存了近几年:

(function(g3, $, window, document, undefined){
   g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* @module {g3.utils}
* @function {g3.utils.type}
* @public
* @param {Type} 'obj' is any type native, host or custom.
* @return {String} Returns a lowercase string representing the object's 
* constructor which is different from word 'object' if they are not custom.
* @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
   if(obj === null)
      return 'null';
   else if(typeof obj === 'undefined')
      return 'undefined';
   return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));
它可能有用

数组中的所有值都表示您想要的值(null、未定义或其他内容),您可以在其中搜索您想要的内容

var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1

尝试使用不同的逻辑。您可以使用下面的代码检查验证的所有四(4)个条件,如NOTNULL、NOBLANK、NOUNDEFINED和not zero。仅在javascript和jquery中使用此代码(!(!(变量)))

function myFunction() {
    var data;  //The Values can be like as null, blank, undefined, zero you can test

    if(!(!(data)))
    {
        alert("data "+data);
    } 
    else 
    {
        alert("data is "+data);
    }
}
在ES6中,使用trim处理空白字符串:

const isEmpty = value => {
    if (typeof value === 'number') return false
    else if (typeof value === 'string') return value.trim().length === 0
    else if (Array.isArray(value)) return value.length === 0
    else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
    else if (typeof value === 'boolean') return false
    else return !value
}

如果您使用的是
TypeScript
,并且不想解释“那些值是
false
,那么这就是您的解决方案:

第一:
从'util'导入{isNullOrUndefined};

然后:
isNullOrUndefined(this.yourVariableName)

请注意:如前所述,现在不推荐使用此选项,请改用
value===undefined | | value==null

是一种非常好的干净的方法,可以在很多地方处理它,也可以用来分配变量

const res = val || 'default value'

一个我非常喜欢的解决方案:

让我们定义一个空白变量为
null
,或
未定义
,或者如果它有长度,则为零,或者如果它是一个对象,则没有键:

function isEmpty (value) {
  return (
    // null or undefined
    (value == null) ||

    // has length and it's zero
    (value.hasOwnProperty('length') && value.length === 0) ||

    // is an Object and has no keys
    (value.constructor === Object && Object.keys(value).length === 0)
  )
}
返回:

  • <
    var variablesWhatILookFor = [null, undefined, ''];
    variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1
    
    function myFunction() {
        var data;  //The Values can be like as null, blank, undefined, zero you can test
    
        if(!(!(data)))
        {
            alert("data "+data);
        } 
        else 
        {
            alert("data is "+data);
        }
    }
    
    function isEmpty(obj) {
        if (typeof obj == 'number') return false;
        else if (typeof obj == 'string') return obj.length == 0;
        else if (Array.isArray(obj)) return obj.length == 0;
        else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
        else if (typeof obj == 'boolean') return false;
        else return !obj;
    }
    
    const isEmpty = value => {
        if (typeof value === 'number') return false
        else if (typeof value === 'string') return value.trim().length === 0
        else if (Array.isArray(value)) return value.length === 0
        else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
        else if (typeof value === 'boolean') return false
        else return !value
    }
    
    return val || 'Handle empty variable'
    
    const res = val || 'default value'
    
    function isEmpty (value) {
      return (
        // null or undefined
        (value == null) ||
    
        // has length and it's zero
        (value.hasOwnProperty('length') && value.length === 0) ||
    
        // is an Object and has no keys
        (value.constructor === Object && Object.keys(value).length === 0)
      )
    }
    
    function isUsable(valueToCheck) {
        if (valueToCheck === 0     || // Avoid returning false if the value is 0.
            valueToCheck === ''    || // Avoid returning false if the value is an empty string.
            valueToCheck === false || // Avoid returning false if the value is false.
            valueToCheck)             // Returns true if it isn't null, undefined, or NaN.
        {
            return true;
        } else {
            return false;
        }
    }
    
    if (isUsable(x)) {
        // It is usable!
    }
    // Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
    if (!isUsable(x)) {
        // It is NOT usable!
    }
    
    function isEmptyObject(valueToCheck) {
        if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
            // Object is empty!
            return true;
        } else {
            // Object is not empty!
            return false;
        }
    }
    
    function isEmptyArray(valueToCheck) {
        if(Array.isArray(valueToCheck) && !valueToCheck.length) {
            // Array is empty!
            return true;
        } else {
            // Array is not empty!
            return false;
        }
    }
    
    function isAllWhitespace(){
        if (valueToCheck.match(/^ *$/) !== null) {
            // Is all whitespaces!
            return true;
        } else {
            // Is not all whitespaces!
            return false;
        }
    }
    
    let customer = {
      name: "Carl",
      details: {
        age: 82,
        location: "Paradise Falls" // detailed address is unknown
      }
    };
    let customerCity = customer.details?.address?.city;
    
    let customer = {
      name: "Carl",
      details: { age: 82 }
    };
    const customerCity = customer?.city ?? "Unknown city";
    console.log(customerCity); // Unknown city
    
    val==null || val==''
    
    function notEmpty(value){
      return (typeof value !== 'undefined' && value.trim().length);
    }