检查的东西isEmpty在Javascript?


83

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

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

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


2
“空”在这里是什么意思?如果不确定,请向我们显示一些代码。
thejh 2011年

1
您是说它还没有初始化吗?
Franz Payer

1
您是说它是否评估为false
Felix Kling

2
你是说它是空字符串吗?
Mark Byers

这是以更易读的方式对PHPsempty()函数的JavaScript实现。stackoverflow.com/a/33319704/3779853
phil294

Answers:


131

如果要测试空字符串:

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

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

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

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

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

如果您同时检查这两个变量,则任一变量为null或未定义:

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

4
不要使用undefined“常量”,因为它根本不是常量。使用typeof myVar === 'undefined'代替。
Guffa 2011年

3
不。如果已声明但未定义变量,则该变量不为null ...未定义。如果检查尚未声明的变量,则会出现运行时错误。另外,var undefined = 1;将破坏您的第三个示例。始终使用typeof并检查"undefined"
gilly3 2011年

@Jhon Woodwrick:那是第一种情况,空字符串。
thejh 2011年

2
if(typeof variable === "undefined")
ncubica 2014年

感谢您的帮助
phani

52

这是一个比您想象的更大的问题。变量可以通过很多方式为空。Kinda取决于您需要了解的内容。

// 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糟糕,谢谢。我认为三重等于是可选的。类型将返回字符串,不会强制执行任何操作。
Hemlock,

确实如此。无论如何,我认为身份检查并没有伤害。:-)
Tomalak

1
(!x)也适用于NaN和[]。(x == null)是对null或未定义的测试。
Patrick Fisher

1
是的,我忘了NaN。我没有意识到null的测试与undefined的测试一样。!x但是对于空数组不是正确的。
Hemlock's

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

5

我发现上面发布的许多解决方案都有潜在的缺点,因此我决定自己编译。
注意:它使用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))
  );
}

真好 您可以指出不同之处,以及如何解决您发现的缺点。
肖恩·梅汉

1
我将需要遍历这里的所有决定。好。与@victorkohl和@kapa函数相比,我的可以比第一级更深入,并报告看起来非空但实际上仅包含空值的复杂对象。范例:[{},0,""]。这里的所有其他解决方案都不过分两线,并且是适用于对象并需要lib的下划线功能。
Oleksii Chekulaiev

4

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

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


3

参见http://underscorejs.org/#isEmpty

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


3

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

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

使用property == null对联合检查nullundefined
SJ00

3

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

为以下项返回true:

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

2

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

假设“空”的意思是null……但是从Asker的问题中不清楚这是什么意思。最好在提供答案之前先阐明这一点,或者至少在回答时将其声明为假设。
米尔(Mir)


0

这取决于您所说的“空”。最常见的模式是检查变量是否未定义。许多人还进行空检查,例如:
if (myVariable === undefined || myVariable === null)...

或者,简称:
if (myVariable || myVariable === null)...


不要使用undefined“常量”,因为它根本不是常量。使用typeof myVar === 'undefined'代替。
Guffa 2011年

这两种形式根本不相同。
卡帕

确实,有一个未定义的类型,但引用标准:引用是已解析的名称绑定。引用由三个部分组成,即基本值,引用名称和布尔值严格引用标记。基本值是未定义的,对象,布尔值,字符串,数字或环境记录(10.2.1)。基本值undefined表示无法将引用解析为绑定。
鲍比D

0
if (myVar == undefined)

可以查看var是否已声明但未初始化。


1
这很危险,因为undefined可以在代码中重新定义(即undefined = true有效)。
Tomalak

不要使用undefined“常量”,因为它根本不是常量。使用typeof myVar === 'undefined'代替。
Guffa 2011年

0

检查未定义:

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

这将使vb的效果变得与众不同IsEmpty。如果myvar包含任何值,甚至为null,空字符串或0,则它不是“空”。

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

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

0

如果您正在寻找与PHPempty函数相同的功能,请查看以下内容:

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


0

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


0

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

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

很奇怪...我还没有看到此解决方案在线发布,但是使用了“!” 应该注意检查大多数值
J Carrillo'1

0

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


我不明白,用户问如何在javascript中检查是否为空,因此我假设用户知道javascript,如果语法已知,则无需解释我的答案?
ismael oliva

添加描述的几句话会更好(:也许别人想也明白了。
RtmY

0

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
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.