在Javascript中检查isEmpty?

新手上路,请多包涵

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

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

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

原文由 Jhon Woodwrick 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 936
2 个回答

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

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

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

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

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

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

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

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

原文由 brettkelly 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 Hemlock 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题