javascript 检查变量是否未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47770877/
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
Check if variable is undefined
提问by theonlygusti
I've tried both these:
我试过这两个:
if foo
if foo[0] == bar.baz[0]
input.form-control-success(type="text")
else
input.form-control-danger(type="text")
else
input(type="text")
unless foo === undefined
if foo[0] == bar.baz[0]
input.form-control-success(type="text")
else
input.form-control-danger(type="text")
else
input(type="text")
But in both cases I get the error
但在这两种情况下,我都收到错误
Cannot read property '0' of undefined
无法读取未定义的属性“0”
on the line if foo[0] == bar.baz[0].
就行了if foo[0] == bar.baz[0]。
The situation is that sometimes foois passed to pug, and sometimes it isn't.
情况是有时foo会传递给哈巴狗,有时则不会。
foois an array when it is passed, and if it is passed I need to do something based on whether it's xthelement is the same as another array's xthelement.
foo当它被传递时是一个数组,如果它被传递,我需要根据它的第x个元素是否与另一个数组的第x个元素相同来做一些事情。
采纳答案by adamz4008
undefined is falsy in js...it looks like bar.baz may be your culprit.
undefined 在 js 中是假的……看起来 bar.baz 可能是你的罪魁祸首。
回答by Crappy
You can use typeofto check if a variable is undefined. It always returns a string.
您可以使用typeof检查变量是否为undefined. 它总是返回一个string.
if (typeof foo === 'undefined') {
console.log('foo is undefined');
}
var foo = ['one', 'two', 'three'];
if (typeof foo !== 'undefined') {
// access elements
console.log(foo[0] + ', ' + foo[1] + ', ' + foo[2]);
}

