如何检查JavaScript中的对象属性是否未定义?
当前回答
我在这里为那些希望得到奇怪答案的人提供了三种方法:
函数为Undefined1(val){尝试{值a;}捕获(e){返回/未定义/测试(e.message);}return false;}函数为Undefined2(val){回来val&&val+“”==“未定义”;}函数未定义3(val){常量defaultVal={};return((input=defaultVal)=>input==defaultVal(val);}功能测试(func){console.group(`test start:`+func.name);console.log(func(未定义));console.log(func(null));console.log(函数(1));console.log(函数(“1”));console.log(函数(0));console.log(func({}));console.log(func(函数(){}));console.groupEnd();}测试(isUndefined1);测试(未定义2);测试(未定义3);
未定义1:
尝试获取输入值的属性,并检查错误消息(如果存在)。如果输入值未定义,则错误消息将为Uncaught TypeError:无法读取未定义的属性“b”。
未定义2:
将输入值转换为字符串以与“undefined”进行比较,并确保其为负值。
未定义3:
在JavaScript中,当输入值完全未定义时,可选参数会起作用。
其他回答
在JavaScript中,存在null和undefined。它们有不同的含义。
undefined表示变量值尚未定义;不知道值是多少。null表示变量值被定义并设置为null(没有值)。
Marijn Haverbeke在他的免费在线书《Eloquent JavaScript》(我的重点)中写道:
还有一个类似的值null,其含义是“此值已定义,但没有值”。undefined和null之间的含义差异主要是学术性的,通常不太有趣。在实际程序中,经常需要检查某个东西是否“有价值”。在这些情况下,可以使用表达式something==undefined,因为即使它们不是完全相同的值,null==undefine也会产生true。
所以,我想最好的检查方法是:
if (something == undefined)
对象财产的工作方式应该相同。
var person = {
name: "John",
age: 28,
sex: "male"
};
alert(person.name); // "John"
alert(person.fakeVariable); // undefined
在ECMAScript 6中引入,我们现在可以使用代理以一种新的方式处理未定义。它可以用于为任何不存在的财产设置默认值,这样我们就不必每次都检查它是否实际存在。
var handler = {
get: function(target, name) {
return name in target ? target[name] : 'N/A';
}
};
var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)
将输出以下文本而不会得到任何未定义。
Name: Kevin , Age: N/A , Gender: N/A
我认为这个问题有很多不正确的答案。与通常的看法相反,“undefined”在JavaScript中不是关键字,实际上可以为其赋值。
正确的代码
执行此测试的最可靠方法是:
if (typeof myVar === "undefined")
这将始终返回正确的结果,甚至可以处理未声明myVar的情况。
退化代码。不要使用。
var undefined = false; // Shockingly, this is completely legal!
if (myVar === undefined) {
alert("You have been misled. Run away!");
}
此外,myVar==undefined将在未声明myVar的情况下引发错误。
读到这里,我很惊讶我没有看到这一点。我已经找到了多种算法可以解决这个问题。
从未定义
如果从未定义对象的值,那么如果将其定义为null或undefined,则将无法返回true。如果您希望为设置为undefined的值返回true,这很有用
if(obj.prop === void 0) console.log("The value has never been defined");
定义为未定义或从未定义
如果您希望使用undefined值定义的值或从未定义的值的结果为true,则可以简单地使用==undefineed
if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");
定义为错误值、未定义、空或从未定义。
通常,人们要求我提供一种算法,以确定某个值是否为假值、未定义值或空值。以下工作。
if(obj.prop == false || obj.prop === null || obj.prop === undefined) {
console.log("The value is falsy, null, or undefined");
}
如果定义了一个新变量,可以用一种优雅的方式将已定义的属性分配给它;如果未定义,则可以将默认值分配给它作为回退。
var a = obj.prop || defaultValue;
如果您有一个函数,它会接收一个额外的配置属性,那么这是合适的:
var yourFunction = function(config){
this.config = config || {};
this.yourConfigValue = config.yourConfigValue || 1;
console.log(this.yourConfigValue);
}
正在执行
yourFunction({yourConfigValue:2});
//=> 2
yourFunction();
//=> 1
yourFunction({otherProperty:5});
//=> 1