【问题标题】:Checking something isEmpty in Javascript?在Javascript中检查isEmpty?
【发布时间】:2022-04-21 17:43:21
【问题描述】:

如何在 Javascript 中检查变量是否为空?

if(response.photo) is empty {
    do something
else {
    do something else
}

response.photo 来自 JSON,有时它可能是空的,空数据单元格!我想检查它是否为空。

【问题讨论】:

  • 这里的“空”是什么意思?如果您不确定,请向我们展示一些代码。
  • 你的意思是如果它还没有初始化?
  • 你的意思是它是否评估为false
  • 你的意思是如果是空字符串吗?
  • 这里是 PHPs empty() 函数的 JavaScript 实现,以更易读的方式。 stackoverflow.com/a/33319704/3779853

标签: javascript jquery


【解决方案1】:

如果您正在测试空字符串:

if(myVar === ''){ // do stuff };

如果您正在检查已声明但未定义的变量:

if(myVar === null){ // do stuff };

如果您正在检查可能未定义的变量:

if(myVar === undefined){ // do stuff };

如果您同时检查两者,即任一变量为空或未定义:

if(myVar == null){ // do stuff };

【讨论】:

  • 不要使用undefined“常量”,因为它根本不是常量。请改用typeof myVar === 'undefined'
  • 不。如果一个变量已被声明但未定义,则它不为空……它是未定义的。如果您检查尚未声明的变量,您将收到运行时错误。此外,var undefined = 1; 将打破您的第三个示例。始终使用typeof 并检查"undefined"
  • @Jhon Woodwrick:这是第一种情况,空字符串。
  • if(typeof variable === "undefined")
  • 感谢您的帮助
【解决方案2】:

这是一个比你想象的更大的问题。变量可以通过多种方式清空。有点取决于你需要知道什么。

// quick and dirty will be true for '', null, undefined, 0, NaN and false.
if (!x) 

// test for null OR undefined
if (x == null)  

// test for undefined OR null 
if (x == undefined) 

// test for undefined
if (x === undefined) 
// or safer test for undefined since the variable undefined can be set causing tests against it to fail.
if (typeof x == 'undefined') 

// test for empty string
if (x === '') 

// if you know its an array
if (x.length == 0)  
// or
if (!x.length)

// BONUS test for empty object
var empty = true, fld;
for (fld in x) {
  empty = false;
  break;
}

【讨论】:

  • @Tomalak 哎呀,谢谢。我认为三等号是可选的。 type of 将返回一个字符串,不会强制任何内容。
  • 确实如此。无论如何,我想身份检查不会受到伤害。 :-)
  • (!x) 也适用于 NaN 和 []。 (x == null) 是对 null 或 undefined 的测试。
  • 对,我忘了 NaN。我没有意识到 null 的测试与 undefined 的测试相同。 !x 不适用于空数组。
【解决方案3】:

这应该涵盖所有情况:

function empty( val ) {

    // test results
    //---------------
    // []        true, empty array
    // {}        true, empty object
    // null      true
    // undefined true
    // ""        true, empty string
    // ''        true, empty string
    // 0         false, number
    // true      false, boolean
    // false     false, boolean
    // Date      false
    // function  false

        if (val === undefined)
        return true;

    if (typeof (val) == 'function' || typeof (val) == 'number' || typeof (val) == 'boolean' || Object.prototype.toString.call(val) === '[object Date]')
        return false;

    if (val == null || val.length === 0)        // null or 0 length array
        return true;

    if (typeof (val) == "object") {
        // empty object

        var r = true;

        for (var f in val)
            r = false;

        return r;
    }

    return false;
}

【讨论】:

  • 我认为空的 GUID 可以通过这个测试。
【解决方案4】:

我发现上面发布的许多解决方案都有潜在的缺陷,所以我决定自己编译。
注意:它使用Array.prototype.some,请检查您的浏览器支持。

如果满足以下条件之一,则以下解决方案认为变量为空:

  1. JS 认为变量等于false,它已经涵盖了很多东西,例如0""[],甚至[""][0]
  2. 值是null 或者它的类型是'undefined'
  3. 它是一个空对象
  4. 它是一个对象/数组,由自身为空的值组成(即分解为基元,每个部分都等于false)。检查递归钻入对象/数组结构。 例如。

    isEmpty({"": 0}) // true
    isEmpty({"": 1}) // false
    isEmpty([{}, {}])  // true
    isEmpty(["", 0, {0: false}]) //true
    

功能代码:

/**
 * Checks if value is empty. Deep-checks arrays and objects
 * Note: isEmpty([]) == true, isEmpty({}) == true, isEmpty([{0:false},"",0]) == true, isEmpty({0:1}) == false
 * @param value
 * @returns {boolean}
 */
function isEmpty(value){
  var isEmptyObject = function(a) {
    if (typeof a.length === 'undefined') { // it's an Object, not an Array
      var hasNonempty = Object.keys(a).some(function nonEmpty(element){
        return !isEmpty(a[element]);
      });
      return hasNonempty ? false : isEmptyObject(Object.keys(a));
    }

    return !a.some(function nonEmpty(element) { // check if array is really not empty as JS thinks
      return !isEmpty(element); // at least one element should be non-empty
    });
  };
  return (
    value == false
    || typeof value === 'undefined'
    || value == null
    || (typeof value === 'object' && isEmptyObject(value))
  );
}

【讨论】:

  • 不错。您可以指出差异以及它如何满足您发现的缺点。
  • 我需要在这里遍历所有决定。好的。与@victorkohl 和@kapa 函数相比,我的函数可以比第一级更深入,并报告看起来非空但实际上只包含类似空值的复杂对象。示例:[{},0,""]。这里的所有其他解决方案都只是两条不走远的线和一个适用于对象并需要库的下划线函数。
【解决方案5】:

这是我最简单的解决方案。

灵感来自 PHP empty 函数

function empty(n){
	return !(!!n ? typeof n === 'object' ? Array.isArray(n) ? !!n.length : !!Object.keys(n).length : true : false);
}

//with number
console.log(empty(0));        //true
console.log(empty(10));       //false

//with object
console.log(empty({}));       //true
console.log(empty({a:'a'}));  //false

//with array
console.log(empty([]));       //true
console.log(empty([1,2]));    //false

//with string
console.log(empty(''));       //true
console.log(empty('a'));      //false

【讨论】:

    【解决方案6】:

    @SJ00 更易读的版本@答案:

    /**
     * Checks if a JavaScript value is empty
     * @example
     *    isEmpty(null); // true
     *    isEmpty(undefined); // true
     *    isEmpty(''); // true
     *    isEmpty([]); // true
     *    isEmpty({}); // true
     * @param {any} value - item to test
     * @returns {boolean} true if empty, otherwise false
     */
    function isEmpty(value) {
        return (
            value === null || // check for null
            value === undefined || // check for undefined
            value === '' || // check for empty string
            (Array.isArray(value) && value.length === 0) || // check for empty array
            (typeof value === 'object' && Object.keys(value).length === 0) // check for empty object
        );
    }
    

    【讨论】:

    • 这会将 Date 对象声明为空
    【解决方案7】:

    http://underscorejs.org/#isEmpty

    isEmpty_.isEmpty(对象) 如果可枚举对象不包含任何值(没有可枚举的自身属性),则返回 true。对于字符串和类似数组的对象,_.isEmpty 检查长度属性是否为 0。

    【讨论】:

      【解决方案8】:

      将来自@inkednm 的答案组合成一个函数:

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

      【讨论】:

      • 使用property == nullnullundefined 进行联合检查
      【解决方案9】:

      对 JSON 密钥的空检查取决于用例。对于一个常见的用例,我们可以测试以下内容:

      1. 不是null
      2. 不是undefined
      3. 不是空字符串''
      4. 不是空对象{}[](数组是一个对象)

      功能:

      function isEmpty(arg){
        return (
          arg == null || // Check for null or undefined
          arg.length === 0 || // Check for empty String (Bonus check for empty Array)
          (typeof arg === 'object' && Object.keys(arg).length === 0) // Check for empty Object or Array
        );
      }
      

      返回真为:

      isEmpty(''); // Empty String
      isEmpty(null); // null
      isEmpty(); // undefined
      isEmpty({}); // Empty Object
      isEmpty([]); // Empty Array
      

      【讨论】:

        【解决方案10】:

        只需将变量放在if条件中,如果变量有任何值,它将返回true,否则返回false。

        if (response.photo){ // if you are checking for string use this if(response.photo == "") condition
         alert("Has Value");
        }
        else
        {
         alert("No Value");
        };
        

        【讨论】:

        • 这假设“空”意味着空......但从提问者的问题中不清楚这就是他们的意思。在提供答案之前,最好先澄清这一点,或者至少在你的答案中将其声明为假设。
        【解决方案11】:

        这样怎么样。

        JSON.stringify({}) === "{}"

        【讨论】:

          【解决方案12】:

          这取决于您所说的“空”是什么意思。最常见的模式是检查变量是否为undefined。很多人也做空检查,例如:
          if (myVariable === undefined || myVariable === null)...

          或者,更短的形式:
          if (myVariable || myVariable === null)...

          【讨论】:

          • 不要使用undefined“常数”,因为它根本不是常数。请改用typeof myVar === 'undefined'
          • 这两种形式根本不一样。
          • 没错,有一个未定义的类型,但引用标准:引用是一个解析的名称绑定。引用由三个部分组成,基值、被引用的名称和布尔值的严格引用标志。基值是未定义的、对象、布尔值、字符串、数字或环境记录 (10.2.1)。基值未定义表示无法将引用解析为绑定。
          【解决方案13】:
          if (myVar == undefined)
          

          将检查变量是否已声明但未初始化。

          【讨论】:

          • 这很危险,因为undefined 可以在代码中重新定义(即undefined = true 有效)。
          • 不要使用undefined“常数”,因为它根本不是常数。请改用typeof myVar === 'undefined'
          【解决方案14】:

          检查未定义:

          if (typeof response.photo == "undefined")
          {
              // do something
          }
          

          这相当于 vb 的IsEmpty。如果 myvar 包含任何值,即使是 null、空字符串或 0,它都不是“空”。

          要检查变量或属性是否存在,例如它是否已被声明,尽管它可能尚未定义,您可以使用in 运算符。

          if ("photo" in response)
          {
              // do something
          }
          

          【讨论】:

            【解决方案15】:

            如果您正在寻找相当于 PHP 的 empty 函数,请查看:

            function empty(mixed_var) {
              //   example 1: empty(null);
              //   returns 1: true
              //   example 2: empty(undefined);
              //   returns 2: true
              //   example 3: empty([]);
              //   returns 3: true
              //   example 4: empty({});
              //   returns 4: true
              //   example 5: empty({'aFunc' : function () { alert('humpty'); } });
              //   returns 5: false
            
              var undef, key, i, len;
              var emptyValues = [undef, null, false, 0, '', '0'];
            
              for (i = 0, len = emptyValues.length; i < len; i++) {
                if (mixed_var === emptyValues[i]) {
                  return true;
                }
              }
            
              if (typeof mixed_var === 'object') {
                for (key in mixed_var) {
                  // TODO: should we check for own properties only?
                  //if (mixed_var.hasOwnProperty(key)) {
                  return false;
                  //}
                }
                return true;
              }
            
              return false;
            }
            

            http://phpjs.org/functions/empty:392

            【讨论】:

              【解决方案16】:

              如果空数组...无键对象...虚假,我会错过什么 const isEmpty = o => Array.isArray(o) && !o.join('').length || typeof o === 'object' && !Object.keys(o).length || !(+值);

              【讨论】:

                【解决方案17】:

                这是一个检查空变量的更简单(简短)的解决方案。此函数检查变量是否为空。提供的变量可能包含混合值(空、未定义、数组、对象、字符串、整数、函数)。

                function empty(mixed_var) {
                 if (!mixed_var || mixed_var == '0') {
                  return true;
                 }
                 if (typeof mixed_var == 'object') {
                  for (var k in mixed_var) {
                   return false;
                  }
                  return true;
                 }
                 return false;
                }
                
                //   example 1: empty(null);
                //   returns 1: true
                
                //   example 2: empty(undefined);
                //   returns 2: true
                
                //   example 3: empty([]);
                //   returns 3: true
                
                //   example 4: empty({});
                //   returns 4: true
                
                //   example 5: empty(0);
                //   returns 5: true
                
                //   example 6: empty('0');
                //   returns 6: true
                
                //   example 7: empty(function(){});
                //   returns 7: false
                

                【讨论】:

                • 奇怪...我还没有看到这个解决方案在网上发布,但是使用了“!”应该注意检查大多数值
                【解决方案18】:

                const isEmpty = val =&gt; val == null || !(Object.keys(val) || val).length;

                【讨论】:

                • 我不明白,用户问如何在javascript中检查空,所以我假设用户知道javascript,如果知道语法就不需要解释我的答案?
                • 多加几句描述会更好(:也许其他人也想明白。
                【解决方案19】:

                function isEmpty(variable) {
                  const type = typeof variable
                  if (variable === null) return true
                  if (type === 'undefined') return true
                  if (type === 'boolean') return false
                  if (type === 'string') return !variable
                  if (type === 'number') return false
                  if (Array.isArray(variable)) return !variable.length
                  if (type === 'object') return !Object.keys(variable).length
                  return !variable
                }

                【讨论】:

                  【解决方案20】:

                  我的解决方案:

                  function isEmpty(object) {
                    return (
                      (!object)
                      || (object === undefined)
                      || (object === null)
                      || (object === '')
                      || ((object?.length !== undefined) && (object.length === 0))
                      || (typeof object === 'object' && Object.keys(object).length === 0) 
                    );
                  }
                  

                  Jest 测试:

                  describe('isEmpty should return `false` when the parameter have some truthy value.', () => {
                    test('Empty objects should return true', () => {
                      expect(utils.isEmpty([])).toBe(true);
                      expect(utils.isEmpty({})).toBe(true);
                      expect(utils.isEmpty('')).toBe(true);
                      expect(utils.isEmpty(undefined)).toBe(true);
                      expect(utils.isEmpty(null)).toBe(true);
                    });
                  
                    test('Truthy objects should return false', () => {
                      expect(utils.isEmpty([1])).toBe(false);
                      expect(utils.isEmpty({a: undefined})).toBe(false);
                      expect(utils.isEmpty({a: 5})).toBe(false);
                      expect(utils.isEmpty({a: 5, b: 6, c: undefined})).toBe(false);
                      expect(utils.isEmpty('f00')).toBe(false);
                      expect(utils.isEmpty('0')).toBe(false);
                    });
                  })
                  

                  【讨论】:

                    猜你喜欢
                    • 2016-03-16
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-01-17
                    • 2016-06-26
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多