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

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

当前回答

var myNewValue = myObject && myObject.child && myObject.child.myValue;

这永远不会抛出错误。如果myObject、child或myValue为空,则myNewValue将为空。不会引发任何错误

其他回答

对于我的案例,我尝试了if null,“”!变量,但它不起作用。

查看下面的代码以从html字段获取文本

var status=$(this).text(); //for example (for my case)

如果状态变量中没有值(没有文本),我试图将值“novalue”设置为状态变量。

以下代码有效。

if(status == false)
{
   status='novalue';
} 

当没有找到satus变量的文本时,上面的代码将“novalue”分配给状态变量

try{

     let vari = obj.propTest; // obj may be don't have propTest property

        ...
} catch(NullException){
    // do something here
}

我认为使用try-catch可以避免任何空检查错误,在Angular或JavaScript中也是如此只是捕获空异常并在其中处理。

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

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

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

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

这是假设0、“”和对象(甚至是空对象和数组)是有效的“值”。

function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

它还将检查空格(“”)以及以下内容:

null,未定义,NaN,空,字符串(“”),0,false