3

不太明白这其中的道理。在以下代码中localStorage,项目的警告为undefined,但如果我使用if(x==undefined)语法它不起作用。有人可以解释是什么问题。谢谢你。

alert(localStorage["x"]);

if(localStorage["x"]=="undefined"){alert("y");}

顶行警报未定义

底线不会提醒

4

3 回答 3

5

它不包含字符串"undefined",它包含类型的值undefined

if (localStorage["x"] == undefined) { alert("y"); }

该值undefined可能在旧浏览器中更改,因此最好的做法是检查类型:

if (typeof localStorage["x"] == 'undefined') { alert("y"); }
于 2012-12-20T01:26:36.180 回答
1

尝试:

if(typeof( localStorage["x"]) == 'undefined'){alert("y");}

或者

if( localStorage["x"]  == undefined){alert("y");}

或者

if( !localStorage["x"] ){alert("y");}
于 2012-12-20T01:26:05.450 回答
1

检查某物的两种方法undefined是:

typeof foo === "undefined"

foo === undefined

在第一种情况下,它将是trueiffoo从未定义值为foois undefined

在第二种情况下,它只会是trueiffoo被定义(否则它会中断)并且它的值是undefined.

根据字符串检查它的值"undefined"根本不一样!

更新:

当我说如果您尝试对未定义的对象文字的属性执行操作时,我想我的意思是它是否完全未定义,而我的意思更像是这样:

obj["x"].toLowerCase()
// or
obj["x"]["y"]

您尝试访问/操作原本是undefined. 在这种情况下,简单地在if语句中进行比较应该没问题,因为对象文字报告值的方式......但与普通的 Javascript 变量有很大不同。

对于对象字面量,如果未定义键(例如“x”),则

obj["x"]

返回 的值undefined,因此 thetypeof和 basic=== undefined检查都将起作用并且是true

未定义或具有值的整体undefined差异与正常变量不同。

如果你有:

var a;
// or
var a = undefined;

那么我之前提供的检查typeof和基本检查都可以正常工作。但是,如果您甚至从未声明过,那么只有支票才能起作用。支票会坏掉。=== undefinedtrueatypeoftrue=== undefined

看看:http: //jsfiddle.net/7npJx/

如果您在控制台中注意到,它会说出b is not defined并打破该if声明。

由于您基本上是使用 来查看对象文字localStorage,因此区分项目是否未定义或具有值的方法undefined是首先使用in。所以,你可以使用:

if (!("x" in localStorage)) {

检查“x”是否根本不是定义的属性,并且:

else if (localStorage["x"] === undefined) {

然后检查它是否已定义但值为undefined. 然后,使用:

else {

将表示localStorage["x"]已定义且不具有 value undefined

但是,在您的代码中,可以使用typeoforin检查(基于您想知道的内容),因为对象文字报告未定义属性的方式。使用基本=== undefined也可以,但正如Guffa指出的那样,实际值可能undefined会被覆盖,然后在此比较中不起作用。当涉及到普通的 Javascript 变量时,typeof检查=== undefined是不一样的。

于 2012-12-20T02:10:10.880 回答