如何测试Javascript中的变量是否已初始化?
问题描述:
如何测试我的javascript代码中的变量是否已初始化?
How do I test if a variable in my javascript code is initialized?
此测试应返回false
This test should return false for
var foo;
和
var foo = 5;
答
if (foo === undefined) { /* not initialized */ }
或偏执狂
if (foo === (void) 0)
这是你可以在JavaScript控制台中测试的东西。只需声明一个变量,然后将其用于(嗯, as )一个表达式。控制台打印的内容是您需要做的一个很好的提示。
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.