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

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

当前回答

最简短的答案可能是

val==null || val==''

如果将右侧更改为val==“”,则空数组将为false。证据

函数isEmpty(val){返回val==null | | val==“”}// ------------//测试// ------------var log=(name,val)=>console.log(`${name}->${isEmpty(val)}`);log('ull',null);log('未定义',未定义);日志('NaN',NaN);日志('“”,“”);日志(“{}”,{});日志('[]',[]);日志(“[1]”,[1]);日志(“[0]”,[0]);日志('[[]]',[[]]);log('true',true);日志('false',false);log('“true”',“true”);日志('“false”',“false”);log(“不确定性”,无限);log('-无限',-无限);日志('1',1);日志('0',0);日志('-1',-1);日志(“1”,“1”);日志(“0”,“0”);日志('“-1”',“-1”);//“void 0”案例console.log('---\n“true”为:',true);console.log('“void 0”为:',void 0);日志(void 0,void 0);//“void 0”是“undefined”-因此我们应该在这里得到TRUE

有关==的更多详细信息(此处来源)

奖金:为什么==比==

写得清晰易懂可理解的代码,使用可接受值的显式列表

val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)

函数isEmpty(val){return val==未定义| | val==null | | val===“”| |(Array.isArray(val)&&val.length==0)}// ------------//测试// ------------var log=(name,val)=>console.log(`${name}->${isEmpty(val)}`);log('ull',null);log('未定义',未定义);日志('NaN',NaN);日志('“”,“”);日志(“{}”,{});日志('[]',[]);日志(“[1]”,[1]);日志(“[0]”,[0]);日志('[[]]',[[]]);log('true',true);日志('false',false);log('“true”',“true”);日志('“false”',“false”);log(“不确定性”,无限);log('-无限',-无限);日志('1',1);日志('0',0);日志('-1',-1);日志(“1”,“1”);日志(“0”,“0”);日志('“-1”',“-1”);//“void 0”案例console.log('---\n“true”为:',true);console.log('“void 0”为:',void 0);日志(void 0,void 0);//“void 0”是“undefined”-因此我们应该在这里得到TRUE

其他回答

对于每一个有类似问题的人来说,以下内容非常有用,我在过去的几年里都把它放在了我的图书馆里:

(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));

我认为使用?操作员稍微干净一点。

var ? function_if_exists() : function_if_doesnt_exist();

最简短的答案可能是

val==null || val==''

如果将右侧更改为val==“”,则空数组将为false。证据

函数isEmpty(val){返回val==null | | val==“”}// ------------//测试// ------------var log=(name,val)=>console.log(`${name}->${isEmpty(val)}`);log('ull',null);log('未定义',未定义);日志('NaN',NaN);日志('“”,“”);日志(“{}”,{});日志('[]',[]);日志(“[1]”,[1]);日志(“[0]”,[0]);日志('[[]]',[[]]);log('true',true);日志('false',false);log('“true”',“true”);日志('“false”',“false”);log(“不确定性”,无限);log('-无限',-无限);日志('1',1);日志('0',0);日志('-1',-1);日志(“1”,“1”);日志(“0”,“0”);日志('“-1”',“-1”);//“void 0”案例console.log('---\n“true”为:',true);console.log('“void 0”为:',void 0);日志(void 0,void 0);//“void 0”是“undefined”-因此我们应该在这里得到TRUE

有关==的更多详细信息(此处来源)

奖金:为什么==比==

写得清晰易懂可理解的代码,使用可接受值的显式列表

val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)

函数isEmpty(val){return val==未定义| | val==null | | val===“”| |(Array.isArray(val)&&val.length==0)}// ------------//测试// ------------var log=(name,val)=>console.log(`${name}->${isEmpty(val)}`);log('ull',null);log('未定义',未定义);日志('NaN',NaN);日志('“”,“”);日志(“{}”,{});日志('[]',[]);日志(“[1]”,[1]);日志(“[0]”,[0]);日志('[[]]',[[]]);log('true',true);日志('false',false);log('“true”',“true”);日志('“false”',“false”);log(“不确定性”,无限);log('-无限',-无限);日志('1',1);日志('0',0);日志('-1',-1);日志(“1”,“1”);日志(“0”,“0”);日志('“-1”',“-1”);//“void 0”案例console.log('---\n“true”为:',true);console.log('“void 0”为:',void 0);日志(void 0,void 0);//“void 0”是“undefined”-因此我们应该在这里得到TRUE

检查默认值

function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function isVariableHaveDefaltVal(variable) {
    if ( typeof(variable) === 'string' ) {  // number, boolean, string, object 
        console.log(' Any data Between single/double Quotes is treated as String ');        
        return (variable.trim().length === 0) ? true : false;
    }else if ( typeof(variable) === 'boolean' ) {
      console.log('boolean value with default value \'false\'');
        return (variable === false) ? true : false;
    }else if ( typeof(variable) === 'undefined' ) {
        console.log('EX: var a; variable is created, but has the default value of undefined.'); 
        return true;
    }else if ( typeof(variable) === 'number' ) { 
        console.log('number : '+variable);
        return (variable === 0 ) ? true : false;
    }else if ( typeof(variable) === 'object' ) {
   //   -----Object-----
        if (typeOfVar(variable) === 'array' && variable.length === 0) {
            console.log('\t Object Array with length = ' + [].length); // Object.keys(variable)
            return true;
        }else if (typeOfVar(variable) === 'string' && variable.length === 0 ) {
            console.log('\t Object String with length = ' + variable.length);
            return true;
        }else if (typeOfVar(variable) === 'boolean' ) {
            console.log('\t Object Boolean = ' + variable);
            return (variable === false) ? true : false;
        }else if (typeOfVar(variable) === 'number' ) {
            console.log('\t Object Number = ' + variable);
            return (variable === 0 ) ? true : false;
        }else if (typeOfVar(variable) === 'regexp' && variable.source.trim().length === 0 ) {
       console.log('\t Object Regular Expression : ');
        return true;
        }else if (variable === null) {
       console.log('\t Object null value');
        return true;
        }
    }
    return false;
}
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
//The "g" flag in the regex will cause all spaces to get replaced.

检查结果:

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函数()来检查哪种类型的对象。

使用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翻译函数TranslateElement是否存在。这相当于:

if (!(typeof google === "undefined" 
 || typeof google.translate === "undefined" 
 || typeof google.translate.TranslateElement === "undefined")) {