在 Javascript 中检查某些东西是空的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4597900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:10:26  来源:igfitidea点击:

Checking something isEmpty in Javascript?

javascriptjquery

提问by Jhon Woodwrick

How can I check if a variable is empty in Javascript? Sorry for the stupid question, but I'm a newbie in Javascript!

如何检查 Javascript 中的变量是否为空?抱歉这个愚蠢的问题,但我是 Javascript 的新手!

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

response.photowas from JSON, and it could be empty sometimes, empty data cells! I want to check if it's empty.

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

回答by inkedmn

If you're testing for an empty string:

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

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

If you're checking for a variable that has been declared, but not defined:

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

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

If you're checking for a variable that may not be defined:

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

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

If you're checking both i.e, either variable is null or undefined:

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

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

回答by Hemlock

This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.

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

// 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;
}

回答by pluto puppy

This should cover all cases:

这应该涵盖所有情况:

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;
}

回答by Oleksii Chekulaiev

I see potential shortcomings in many solutions posted above, so I decided to compile my own.
Note:it uses Array.prototype.some, check your browser support.

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

Solution below considers variable empty if one of the following is true:

如果以下情况之一为真,则下面的解决方案将变量视为空:

  1. JS thinks that variable is equal to false, which already covers many things like 0, "", [], and even [""]and [0]
  2. Value is nullor it's type is 'undefined'
  3. It is an empty Object
  4. It is an Object/Array consisting onlyof values that are empty themselves (i.e. broken down to primitives each part of it equals false). Checks drill recursively into Object/Array structure. E.g.

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

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

Function code:

功能代码:

/**
 * 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))
  );
}

回答by Lo HaBuyshan

See http://underscorejs.org/#isEmpty

http://underscorejs.org/#isEmpty

isEmpty_.isEmpty(object) Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.

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

回答by Crashalot

Combining answers from @inkednm into one function:

将@inkednm 的答案合并为一个函数:

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

回答by Prabu samvel

Here my simplest solution.

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

Inspired by PHPemptyfunction

PHPempty函数启发

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

回答by Deepak M.S.

just put the variable inside the if condition, if variable has any value it will return true else false.

只需将变量放在 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");
};

回答by Tibin Thomas

What about doing like this.

这样做怎么样。

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

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

回答by J Carrillo

Here's a simpler(short) solution to check for empty variables. This function checks if a variable is empty. The variable provided may contain mixed values (null, undefined, array, object, string, integer, function).

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

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