哪一种方法检查变量是否已初始化是更好/正确的方法? (假设变量能够容纳任何内容(字符串,整数,对象,函数等)。 浏览器
if (elem) { // or !elem
要么 函数
if (typeof(elem) !== 'undefined') {
要么 测试
if (elem != null) {
在JavaScript中,能够定义一个变量,可是将其值保留为undefined
,所以最多见的答案在技术上并不正确,而是执行如下操做: spa
if (typeof v === "undefined") { // no variable "v" is defined in the current scope // *or* some variable v exists and has been assigned the value undefined } else { // some variable (global or local) "v" is defined in the current scope // *and* it contains a value other than undefined }
这可能足以知足您的目的。 如下测试具备更简单的语义,这使得更容易精确地描述代码的行为并亲自理解(若是您关心这样的事情): code
if ("v" in window) { // global variable v is defined } else { // global variable v is not defined }
固然,这假定您正在浏览器中运行(其中window
是全局对象的名称)。 可是,若是您想像这样的全局变量,则多是在浏览器中。 从主观上讲, 'name' in window
使用'name' in window
样式上与使用window.name
引用全局变量一致。 做为window
属性而不是变量访问全局变量,可使您在代码中引用的未声明变量的数量最少(以利于衬里),并避免全局变量被局部变量覆盖的可能性。 另外,若是全局对象使您的皮肤爬行,则仅用此相对较长的棍子接触它们时,您可能会感到更温馨。 对象
if (typeof console != "undefined") { ... }
或更好 ip
if ((typeof console == "object") && (typeof console.profile == "function")) { console.profile(f.constructor); }
适用于全部浏览器 字符串
在问题概述的特定状况下, it
typeof window.console === "undefined"
与...相同 io
window.console === undefined
我更喜欢后者,由于它更短。
请注意,咱们仅在全局范围(在全部浏览器中都是window
对象)中查找console
。 在这种特殊状况下,这是可取的。 咱们不但愿在其余地方定义console
。
@BrianKelley在他的出色回答中解释了技术细节。 我仅添加了缺乏的结论,并将其摘要为更易于阅读的内容。
最高答案是正确的,请使用typeof。
可是,我想指出的是,在JavaScript中, undefined
是可变的(出于某些不敬虔的缘由)。 所以,仅检查varName !== undefined
就有可能没法老是按预期返回,由于其余库可能已更改成undefined。 一些答案(@skalee的答案)彷佛更喜欢不使用typeof
,这可能会给您带来麻烦。
“旧”的方式来处理这个问题被宣布不定位为VAR,以抵消任何潜在的静音/的压倒一切的undefined
。 可是,最好的方法仍然是使用typeof
由于它将忽略其余代码中全部undefined
覆盖。 尤为是若是您正在编写要在野外使用的代码,那么谁又知道该页面上可能还会运行什么……
您可使用typeof
运算符。
例如,
var dataSet; alert("Variable dataSet is : " + typeof dataSet);
上面的代码片断将返回相似的输出
变量dataSet是:未定义。