如何检查JavaScript中的对象属性是否未定义?
当前回答
我没有看到(希望我没有错过)任何人在物业前检查该对象。因此,这是最短和最有效的(虽然不一定是最清楚的):
if (obj && obj.prop) {
// Do something;
}
如果obj或obj.prop为undefined、null或“falsy”,If语句将不执行代码块。这通常是大多数代码块语句(在JavaScript中)所需的行为。
更新:(2021 7月2日)
最新版本的JavaScript为可选链接:?。
这可能是检查对象财产是否存在的最明确、最有效的方法。
裁判:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
其他回答
if (somevariable == undefined) {
alert('the variable is not defined!');
}
您也可以将其转换为函数,如下所示:
function isset(varname){
return(typeof(window[varname]) != 'undefined');
}
您可以像这样使用JavaScript对象函数:
var ojb ={
age: 12
}
if(ojb.hasOwnProperty('name')){
console.log('property exists and is not undefined');
}
如果获得该属性或该属性未定义,则上述方法返回true。
简单地说,JavaScript中没有定义的任何东西都是未定义的,无论它是Object/Array中的属性还是只是一个简单的变量。。。
JavaScript具有类型of,因此很容易检测未定义的变量。
只需检查typeof whatever==“undefined”,就会返回布尔值。
这就是AngularJs v.1x中著名的函数isUndefined()的编写方式:
function isUndefined(value) {return typeof value === 'undefined';}
因此,当您看到函数接收到一个值时,如果定义了该值,它将返回false,否则对于未定义的值,返回true。
让我们看看传递值时会得到什么结果,包括如下所示的对象财产,这是我们拥有的变量列表:
var stackoverflow = {};
stackoverflow.javascipt = 'javascript';
var today;
var self = this;
var num = 8;
var list = [1, 2, 3, 4, 5];
var y = null;
我们如下所示进行检查,您可以在他们面前看到结果作为评论:
isUndefined(stackoverflow); //false
isUndefined(stackoverflow.javascipt); //false
isUndefined(today); //true
isUndefined(self); //false
isUndefined(num); //false
isUndefined(list); //false
isUndefined(y); //false
isUndefined(stackoverflow.java); //true
isUndefined(stackoverflow.php); //true
isUndefined(stackoverflow && stackoverflow.css); //true
正如您所看到的,我们可以在代码中使用类似的东西来检查任何情况,正如前面所提到的,您可以在您的代码中简单地使用typeof,但是如果您反复使用它,请创建一个像我共享的angular sample这样的函数,并将其作为以下DRY代码模式继续重用。
还有一件事,要检查真实应用程序中对象的属性,即使您不确定该对象是否存在,也要先检查对象是否存在。
如果您检查对象的属性而该对象不存在,将抛出错误并停止整个应用程序的运行。
isUndefined(x.css);
VM808:2 Uncaught ReferenceError: x is not defined(…)
如此简单,您可以像下面这样包装在if语句中:
if(typeof x !== 'undefined') {
//do something
}
也等于在Angular 1.x中定义的。。。
function isDefined(value) {return typeof value !== 'undefined';}
其他javascript框架(如下划线)也有类似的定义检查,但如果您尚未使用任何框架,我建议您使用typeof。
我还从MDN中添加了这一部分,它提供了关于typeof、undefined和void(0)的有用信息。
严格相等和未定义您可以使用undefined和严格相等和不相等运算符来确定变量是否具有一个值。在以下代码中,未定义变量xif语句的计算结果为true。
var x;
if (x === undefined) {
// these statements execute
}
else {
// these statements do not execute
}
注意:严格等式运算符而不是标准等式这里必须使用运算符,因为x==undefined还检查x为空,而严格相等不为空。null不等于未定义。有关详细信息,请参见比较运算符。
运算符类型和未定义或者,可以使用typeof:
var x;
if (typeof x === 'undefined') {
// these statements execute
}
使用typeof的一个原因是,如果尚未声明变量。
// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
// these statements execute
}
if (x === undefined) { // throws a ReferenceError
}
然而,这种技术应该避免。JavaScript是静态作用域语言,因此知道是否声明了变量可以通过查看它是否在封闭上下文中声明来读取。这个唯一的例外是全局范围,但全局范围与全局对象,因此检查全局上下文可以通过检查全局对象(例如,使用in运算符)。
无效运算符和未定义void运算符是第三种选择。
var x;
if (x === void 0) {
// these statements execute
}
// y has not been declared before
if (y === void 0) {
// throws a ReferenceError (in contrast to `typeof`)
}
更多>此处
检查属性值是否为未定义的特殊值的通常方法是:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
要检查对象是否实际上没有这样的属性,并且当您尝试访问它时,默认情况下会返回undefined:
if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
要检查与标识符关联的值是否为未定义的特殊值,或者该标识符是否尚未声明:
if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
注意:最后一个方法是引用未声明的标识符而不出现早期错误的唯一方法,这与值为undefined不同。
在ECMAScript 5之前的JavaScript版本中,全局对象上名为“undefined”的属性是可写的,因此,如果不小心重新定义了foo==undefineed,则简单的检查可能会出现意外的行为。在现代JavaScript中,属性是只读的。
然而,在现代JavaScript中,“undefined”不是关键字,因此函数内部的变量可以命名为“undefine”,并隐藏全局属性。
如果您担心这种(不太可能的)边缘情况,可以使用void运算符获取特殊的未定义值本身:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
我很惊讶我还没有看到这个建议,但它比使用typeof测试更具特异性。如果您需要知道对象属性是用undefined初始化的还是从未初始化过,请使用Object.getOwnPropertyDescriptor():
// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');
if (typeof descriptor === 'undefined') {
// was never initialized
} else if (typeof descriptor.value === 'undefined') {
if (descriptor.get || descriptor.set) {
// is an accessor property, defined via getter and setter
} else {
// is initialized with `undefined`
}
} else {
// is initialized with some other value
}