如何测试 Javascript 中的变量是否已初始化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10181619/
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
How do I test if a variable in Javascript is initialized?
提问by John Hoffman
How do I test if a variable in my javascript code is initialized?
如何测试我的 javascript 代码中的变量是否已初始化?
This test should return false for
此测试应返回 false
var foo;
and true for
和真的
var foo = 5;
回答by Pointy
if (foo === undefined) { /* not initialized */ }
or for the paranoid
或偏执狂
if (foo === (void) 0)
This is the sort of thing that you can test right in your JavaScript console. Just declare a variable and then use it in (well, as) an expression. What the console prints is a good hint to what you need to do.
这是您可以直接在 JavaScript 控制台中测试的类型。只需声明一个变量,然后在(好吧,作为)表达式中使用它。控制台打印的内容很好地提示了您需要做什么。
回答by Woody
Using the typeof operator you can use the following test:
使用 typeof 运算符,您可以使用以下测试:
if (typeof foo !== 'undefined') {
// foo has been set to 5
}
else {
// foo has not been set
}
I find the jQuery fundamentals JavaScript Basicschapter really useful.
我发现 jQuery 基础JavaScript 基础一章非常有用。
I hope this helps.
我希望这有帮助。