检测未定义的对象属性
检查JavaScript中的对象属性是否未定义的最佳方法是什么?
解决方案
回答
if (somevariable == undefined) { alert('the variable is not defined!'); }
我们还可以使其成为一个函数,如下所示:
function isset(varname){ return(typeof(window[varname]) != 'undefined'); }
回答
在JavaScript中,为null,未定义。它们具有不同的含义。
- 未定义表示尚未定义变量值;目前尚不清楚该值是多少。
- null表示已定义变量值并将其设置为null(无值)。
Marijn Haverbeke在他的免费在线书" Eloquent JavaScript"(强调我的)中指出:
There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.
因此,我认为检查某些内容是否未定义的最佳方法是:
if (something == undefined)
希望这可以帮助!
编辑:响应编辑,对象属性应该以相同的方式工作。
var person = { name: "John", age: 28, sex: "male" }; alert(person.name); // "John" alert(person.fakeVariable); // undefined
回答
解决方法不正确。在JavaScript中,
null == undefined
将返回true,因为它们都"强制转换"为布尔值并且为false。正确的方法是检查
if (something === undefined)
这是身份运算符...
回答
使用:
if (typeof something === "undefined") { alert("something is undefined"); }
如果对象变量具有某些属性,则可以使用类似的方法:
if (typeof my_obj.someproperties === "undefined"){ console.log('the property is not available...'); // print into console }
从ECMAScript 5开始," undefined"无法被覆盖,因此" my_obj === undefined"也可以工作,但前提是存在" my_obj"。这可能会或者可能不会,因为如果需要此语义,我们也可以使用`null'(请参阅JavaScript中null和undefined之间的区别是什么?)。但是对于对象属性,无论该属性是否存在,它都可以工作。
回答
function isUnset(inp) { return (typeof inp === 'undefined') }
如果设置了变量,则返回false;如果未定义,则返回true。
然后使用:
if (isUnset(var)) { // initialize variable here }
回答
if ( typeof( something ) == "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的情况下,myVar === undefined
会引发错误。
回答
我不确定将===
和typeof
一起使用的起源是什么,按照惯例,我看到它在许多库中都使用过,但是typeof运算符会返回字符串文字,并且我们知道那么我们为什么还要输入check呢?
typeof x; // some string literal "string", "object", "undefined" if (typeof x === "string") { // === is redundant because we already know typeof returns a string literal if (typeof x == "string") { // sufficient