是否有一个通用的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")) {

其他回答

我想这会让你的代码看起来更简单

检查变量是否未定义或为空

var a=undefined, b=null, c='hello world', d;
if(a !== (a ?? {})) { /**/ } // true
if(b !== (b ?? {})) { /**/ } // true
if(c !== (c ?? {})) { /**/ } // false
if(d !== (d ?? {})) { /**/ } // true

检查变量是否未定义或为空

var a=undefined, b=null, c='hello world', d;
if(a === (a ?? {})) { /**/ } // false
if(b === (b ?? {})) { /**/ } // false
if(c === (c ?? {})) { /**/ } // true
if(d === (d ?? {})) { /**/ } // false

如果您喜欢纯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)

尝试使用不同的逻辑。您可以使用下面的代码检查所有四(4)个验证条件,如非空、非空、未定义和非零。仅在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);
    }
}

这还包括空数组和空对象

null,未定义,“”,0,[],{}

isEmpty = (value) => (!value  || (typeof v === 'object' &&
   Object.keys(value).length < 1));

这是我检查数据是否为空的解决方案。

const _isEmpty = (data) => {
  return (
    // this way we can also check for undefined values. null==undefined is true
    data == null ||
    data == "" ||
    (Array.isArray(data) && data.length === 0) ||
    // we want {} to be false. we cannot use !! because !!{} turns to be true
    // !!{}=true and !!{name:"yilmaz"}=true. !! does not work ofr objects
    (data.constructor === Object && Object.keys(data).length === 0)

  );
};