Sam*_*iew 1642 javascript variables if-statement initialization undefined
检查变量是否已初始化的哪种方法更好/更正?(假设变量可以包含任何内容(字符串,整数,对象,函数等))
if (elem) { // or !elem
Run Code Online (Sandbox Code Playgroud)
要么
if (typeof(elem) !== 'undefined') {
Run Code Online (Sandbox Code Playgroud)
要么
if (elem != null) {
Run Code Online (Sandbox Code Playgroud)
Jim*_*uls 2905
你想要的typeof
操作.特别:
if (typeof variable !== 'undefined') {
// the variable is defined
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*iew 816
该typeof
运营商将检查变量确实是不确定的.
if (typeof variable === 'undefined') {
// variable is undefined
}
Run Code Online (Sandbox Code Playgroud)
该typeof
运营商,不同于其他运营商,不会抛出的ReferenceError与未声明的变量使用时例外.
但是,请注意typeof null
将返回"object"
.我们必须小心避免将变量初始化为错误null
.为了安全起见,这是我们可以使用的:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
Run Code Online (Sandbox Code Playgroud)
有关使用严格比较===
而不是简单相等的更多信息==
,请参阅:
在JavaScript比较中应使用哪个等于运算符(== vs ===)?
小智 207
在JavaScript中,可以定义一个变量,但保留该值undefined
,因此最常见的答案在技术上并不正确,而是执行以下操作:
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
}
Run Code Online (Sandbox Code Playgroud)
这可能足以满足您的目的.以下测试具有更简单的语义,这使得更容易精确描述代码的行为并自己理解(如果您关心这些事情):
if ("v" in window) {
// global variable v is defined
} else {
// global variable v is not defined
}
Run Code Online (Sandbox Code Playgroud)
当然,这假设您在浏览器中运行(其中window
是全局对象的名称).但是,如果你正在使用像这样的全局变量,你可能在浏览器中.主观上,使用'name' in window
在风格上与使用window.name
引用全局变量一致.将全局变量作为属性window
而不是变量访问允许您最小化在代码中引用的未声明变量的数量(为了利用linting),并避免全局被局部变量遮蔽的可能性.此外,如果全球化使你的皮肤爬行,你可能会感觉更舒服只用这个相对长的棍子接触它们.
Ali*_*eza 196
在许多情况下,使用:
if (elem) { // or !elem
Run Code Online (Sandbox Code Playgroud)
会为你做这个工作!...这将检查以下案例:
undefined
''
因此它将覆盖所有情况,但总有一些奇怪的情况,我们也想覆盖,例如,一个带空格的字符串,就像这个' '
,这将在javascript中定义,因为它在字符串中有空格...例如,在这种情况下,您使用trim()添加一个检查,如:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
Run Code Online (Sandbox Code Playgroud)
此外,这些检查仅用于值,因为对象和数组在Javascript中的工作方式不同,空数组[]
和空对象{}
始终为true.
我创建了下面的图像,以显示答案的简要说明:
Dav*_*ang 116
在大多数情况下,您将使用:
elem != null
Run Code Online (Sandbox Code Playgroud)
不同于简单的if (elem)
,它允许0
,false
,NaN
和''
,但拒绝null
或undefined
,使之成为一个参数的存在,或对象的属性的好,一般测试.
其他检查也不正确,它们只是有不同的用途:
if (elem)
:如果可以被用于elem
保证是一个对象,或者如果false
,0
等被认为是"默认"值(因此等同于undefined
或null
).
typeof elem == 'undefined'
可以在指定的null
对未初始化的变量或属性具有不同含义的情况下使用.
elem
var
window
同样有用的是严格比较undefined
:
if (elem === undefined) ...
Run Code Online (Sandbox Code Playgroud)
但是,因为全局undefined
可以用另一个值覆盖,所以最好undefined
在使用它之前在当前作用域中声明该变量:
var undefined; // really undefined
if (elem === undefined) ...
Run Code Online (Sandbox Code Playgroud)
要么:
(function (undefined) {
if (elem === undefined) ...
})();
Run Code Online (Sandbox Code Playgroud)
这种方法的第二个优点是JS minifiers可以将undefined
变量减少为单个字符,每次节省几个字节.
Joh*_*ers 67
这是一个非常灵活的解决方案,用于测试变量是否存在并已初始化:
var setOrNot = typeof variable !== typeof undefined;
Run Code Online (Sandbox Code Playgroud)
它最常与三元运算符结合使用,以便在某个变量尚未初始化时设置默认值:
var dark = typeof darkColor !== typeof undefined ? darkColor : "black";
Run Code Online (Sandbox Code Playgroud)
不幸的是,你不能简单地将你的支票封装在一个函数中.
您可能会想到这样的事情:
function isset(variable) {
return typeof variable !== typeof undefined;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您正在调用eg,则会产生参考错误.isset(foo)
和变量foo
尚未定义,因为您无法将不存在的变量传递给函数:
未捕获的ReferenceError:未定义foo
虽然我们的isset
函数不能用于测试变量是否存在(由于上面解释的原因),但它确实允许我们测试函数的参数是否未定义:
var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};
test(a);
// OUTPUT :
// ------------
// TRUE
// FALSE
Run Code Online (Sandbox Code Playgroud)
即使没有y
传递给函数的值test
,我们的isset
函数在这个上下文中也能很好地工作,因为y
在函数test
中它被称为undefined
值.
Fre*_*ndt 64
window
过多hasOwnProperty
答案的替代方法是使用varname
当然检查对象(JS中的几乎所有东西)是否具有属性,即变量(以及其他内容).
该
typeof
方法返回一个布尔值,指示对象是否具有指定的属性作为自己的(不是继承的)属性.来自Object的每个对象都继承该
var varname = value;
方法.此方法可用于确定对象是否具有指定的属性作为该对象的直接属性; 与in运算符不同,此方法不会检查对象的原型链.
// Globally established, therefore, properties of window
var foo = "whatever", // string
bar = false, // bool
baz; // undefined
// window.qux does not exist
console.log( [
window.hasOwnProperty( "foo" ), // true
window.hasOwnProperty( "bar" ), // true
window.hasOwnProperty( "baz" ), // true
window.hasOwnProperty( "qux" ) // false
] );
Run Code Online (Sandbox Code Playgroud)
有什么好处的hasOwnProperty()
是,在调用它时,我们不使用可能尚未定义的变量 - 这当然是问题的一半.
虽然不是经常的完美或理想的解决方案,在某些情况下,它只是工作!
Raj*_*dev 41
当您执行简单的任务和相关检查时,还有另一种简便方法可以检查这一点.只需使用条件(三元)运算符.
var values = typeof variable !== 'undefined' ? variable : '';
Run Code Online (Sandbox Code Playgroud)
当您尝试使用引用变量的实例赋值声明Global变量时,这也会有所帮助.
如果你想检查变量不应该undefined
或null
.然后执行以下检查.
当声明变量时,如果要检查该值,这甚至是简单的: 它将执行undefined
并null
一起检查.
var values = variable ? variable : '';
Run Code Online (Sandbox Code Playgroud)
Ala*_*nse 29
这取决于您是否只关心变量已被定义或者您是否希望它具有有意义的值.
检查类型是否未定义将检查变量是否已定义.
=== null
或者!== null
只检查变量的值是否正确null
.
== null
或!= null
将检查值undefined
或null
.
if(value)
将检查变量是undefined
,null
,0
,或一个空字符串.
Kam*_*ski 19
如果根本没有定义变量(例如:定义全局变量的外部库尚未加载 - 例如谷歌地图),您可以使用 try-catch 块进行检查而不中断代码执行,如下所示(您不需要use strict
模式)
try{
notDefinedVariable;
} catch(e) {
console.log('detected: variable not exists');
}
console.log('but the code is still executed');
notDefinedVariable; // without try-catch wrapper code stops here
console.log('code execution stops. You will NOT see this message on console');
Run Code Online (Sandbox Code Playgroud)
奖励:(参考其他答案)为什么===
比==
(来源)更清楚
use*_*850 16
未声明(未定义)测试变量的简短方法是
if (typeof variable === "undefined") {
...
}
Run Code Online (Sandbox Code Playgroud)
我发现它对于检测在浏览器外部运行的脚本(没有声明window
变量)很有用。
小智 12
最高的答案是正确的,使用typeof.
但是,我想指出的是,在JavaScript中undefined
是可变的(出于一些不道德的原因).因此,仅仅进行检查varName !== undefined
有可能不会像您期望的那样始终返回,因为其他库可能已经更改未定义.一些答案(@ skalee的,一个),似乎不喜欢不使用typeof
,这可能会让人陷入困境.
处理这种情况的"旧"方式是声明未定义为var以抵消任何潜在的静音/覆盖undefined
.但是,最好的方法仍然是使用,typeof
因为它将忽略undefined
来自其他代码的任何覆盖.特别是如果您正在编写代码以便在野外使用,谁知道页面上还有什么可以运行...
小智 11
if (typeof console != "undefined") {
...
}
Run Code Online (Sandbox Code Playgroud)
或更好
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
Run Code Online (Sandbox Code Playgroud)
适用于所有浏览器
为了促成辩论,如果我知道变量应该是我总是喜欢的字符串或对象if (!variable)
,那么检查它是否是假的.这可以带来更干净的代码,例如:
if (typeof data !== "undefined" && typeof data.url === "undefined") {
var message = 'Error receiving response';
if (typeof data.error !== "undefined") {
message = data.error;
} else if (typeof data.message !== "undefined") {
message = data.message;
}
alert(message);
}
Run Code Online (Sandbox Code Playgroud)
..可以简化为:
if (data && !data.url) {
var message = data.error || data.message || 'Error receiving response';
alert(message)
}
Run Code Online (Sandbox Code Playgroud)
很难区分undefined和null.当您想要指示变量没有特定值时,Null是您可以分配给变量的值.Undefined 是一个特殊值,它将是未分配变量的默认值.
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _null);
Null是JavaScript中的值并typeof null
返回"object"
因此,如果传递空值,则接受的答案将不起作用.如果传递空值,则需要为空值添加额外检查:
if ((typeof variable !== "undefined") && (variable !== null))
{
// the variable is defined and not null
}
Run Code Online (Sandbox Code Playgroud)
小智 7
你可以使用typeof
运营商.
例如,
var dataSet;
alert("Variable dataSet is : " + typeof dataSet);
Run Code Online (Sandbox Code Playgroud)
上面的代码片段将返回输出
变量dataSet是:undefined.
最强大的'它定义'检查是与typeof
if (typeof elem === 'undefined')
Run Code Online (Sandbox Code Playgroud)
如果您只是检查已定义的变量以指定默认值,那么通常可以执行以下操作:
elem = elem || defaultElem;
Run Code Online (Sandbox Code Playgroud)
它通常很好用,请参阅:在javascript中设置默认值的惯用法
还有一个使用typeof关键字的班轮:
elem = (typeof elem === 'undefined') ? defaultElem : elem;
Run Code Online (Sandbox Code Playgroud)
这些答案(除了Fred Gandt解决方案)都不正确或不完整.
假设我需要variableName;
携带一个undefined
值,因此它已经以某种方式声明,var variableName;
这意味着它已经初始化了 ; - 如何检查是否已经申报?
或者甚至更好 - 如何通过一次调用立即检查"Book1.chapter22.paragraph37"是否存在,但不会引发参考错误?
我们使用最强大的JasvaScript运算符,in运算符:
"[variable||property]" in [context||root]
>> true||false
Run Code Online (Sandbox Code Playgroud)
在AJAX达到普及的时候,我编写了一个方法(后来命名)isNS(),它能够确定命名空间是否存在,包括对属性名称的深度测试,如"Book1.chapter22.paragraph37"等等.
但由于它以前已经发布,并且由于其非常重要,它值得在一个单独的线程中发布,我不会在这里发布,但会提供关键字(javascript + isNS),它将帮助您找到源代码,支持所有必要的解释.
在问题中概述的特定情况下,
typeof window.console === "undefined"
Run Code Online (Sandbox Code Playgroud)
是完全相同的
window.console === undefined
Run Code Online (Sandbox Code Playgroud)
我更喜欢后者,因为它更短.
请注意,我们console
只在全局范围内查找(这是window
所有浏览器中的对象).在这种特殊情况下,这是可取的.我们不希望console
在其他地方定义.
@BrianKelley在他的回答中解释了技术细节.我只是添加了缺乏结论并将其消化为易于阅读的内容.
我的偏好是typeof(elem) != 'undefined' && elem != null
.
无论如何选择,考虑将支票放入这样的功能中
function existy (x) {
return typeof (x) != 'undefined' && x != null;
}
Run Code Online (Sandbox Code Playgroud)
如果您不知道变量已声明,请继续 typeof (x) != 'undefined' && x != null;
如果您知道变量已声明但可能不存在,则可以使用
existy(elem) && doSomething(elem);
Run Code Online (Sandbox Code Playgroud)
您正在检查的变量有时可能是嵌套属性.你可以使用prop || {}下线检查有问题的财产:
var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
Run Code Online (Sandbox Code Playgroud)
在每个属性使用(...'|| {}').nextProp之后,丢失的属性不会抛出错误.
或者你可以使用像 existy(o) && existy(o.p) && existy(o.p.q) && doSomething(o.p.q)
为了检查变量是否已经声明/设置,我做了这个肮脏的把戏。
我什至没有找到一种将代码提取到函数中的方法eval
。
"use strict";
// var someVar;
var declared;
try {
someVar;
declared = true;
} catch(e) {
declared = false;
}
if (declared) {
console.log("someVar is declared; now has the value: " + someVar);
} else {
console.log("someVar is not declared");
}
Run Code Online (Sandbox Code Playgroud)
我根据对象使用两种不同的方式。
if( !variable ){
// variable is either
// 1. '';
// 2. 0;
// 3. undefined;
// 4. null;
// 5. false;
}
Run Code Online (Sandbox Code Playgroud)
有时我不想将空字符串评估为falsey,所以我使用这种情况
function invalid( item ){
return (item === undefined || item === null);
}
if( invalid( variable )){
// only here if null or undefined;
}
Run Code Online (Sandbox Code Playgroud)
如果需要相反的情况,则首先将!variable变为!! variable,而在无效函数中===变为!=且函数名称更改为notInvalid。
归档时间: |
|
查看次数: |
1417315 次 |
最近记录: |