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

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

当前回答

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

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")) {

其他回答

您可以只检查变量是否具有真实值。这意味着

if (value) {
    // do something..
}

如果值不是:

无效的未定义NaN公司空字符串(“”)0假的

上面的列表表示ECMA-/Javascript中所有可能的错误值。在ToBoolean部分的规范中找到它。

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

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

如果您可以确定至少声明了一个变量,那么应该直接检查它是否具有如上所示的真实值。

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

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

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

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

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

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

以下代码有效。

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

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

return val || 'Handle empty variable'

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

const res = val || 'default value'
function isEmpty(val){
    return !val;
}

但是这个解决方案是过度设计的,如果您不想稍后根据业务模型的需要修改函数,那么直接在代码中使用它会更干净:

if(!val)...