在Javascript中检查一下isEmpty?

Jho*_*ick 70 javascript jquery

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

if(response.photo) is empty {
    do something
else {
    do something else
}
Run Code Online (Sandbox Code Playgroud)

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

ink*_*dmn 109

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

if(myVar === ''){ // do stuff };
Run Code Online (Sandbox Code Playgroud)

如果要检查已声明但未定义的变量:

if(myVar === null){ // do stuff };
Run Code Online (Sandbox Code Playgroud)

如果要检查可能未定义的变量:

if(myVar === undefined){ // do stuff };
Run Code Online (Sandbox Code Playgroud)

如果你同时检查ie,则变量为null或未定义:

if(myVar == null){ // do stuff };
Run Code Online (Sandbox Code Playgroud)

  • 不要使用`undefined`"常量",因为它根本不是常数.请使用`typeof myVar ==='undefined'. (3认同)
  • 不.如果已声明但未定义变量,则它不为null ...它是未定义的.如果检查尚未声明的变量,则会出现运行时错误.另外,`var undefined = 1;`将打破你的第三个例子.总是使用`typeof`并检查`"undefined"`. (3认同)
  • `if(typeof variable ==="undefined")` (2认同)

Hem*_*ock 47

这是一个比你想象的更大的问题.变量可以在很多方面清空.有点取决于你需要知道什么.

// 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;
}
Run Code Online (Sandbox Code Playgroud)

  • +1.应该是`typeof x ==="undefined"`. (4认同)
  • (!x) 对于 NaN 和 [] 也成立。(x == null) 是 null 或 undefined 的测试。 (2认同)
  • 对了,我忘了 NaN 了。我没有意识到 null 的测试与 undefined 的测试是一样的。但对于空数组来说,`!x` 并不成立。 (2认同)

plu*_*ppy 11

这应涵盖所有情况:

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;
}
Run Code Online (Sandbox Code Playgroud)


Ole*_*iev 5

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

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

  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
    
    Run Code Online (Sandbox Code Playgroud)

功能代码:

/**
 * 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))
  );
}
Run Code Online (Sandbox Code Playgroud)