如何检查 Javascript 中的变量是否为空?
if(response.photo) is empty {
do something
else {
do something else
}
response.photo
来自 JSON,有时它可能是空的,空数据单元格!我想检查它是否为空。
原文由 Jhon Woodwrick 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何检查 Javascript 中的变量是否为空?
if(response.photo) is empty {
do something
else {
do something else
}
response.photo
来自 JSON,有时它可能是空的,空数据单元格!我想检查它是否为空。
原文由 Jhon Woodwrick 发布,翻译遵循 CC BY-SA 4.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 许可协议
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
如果您正在测试空字符串:
如果您正在检查已声明但未定义的变量:
如果您正在检查可能未定义的变量:
如果您同时检查两者,即任一变量为空或未定义: