我有三个页面使用了相同的代码,其中一个页面上的变量不存在,另外两个页面上的变量ticketType的值是1或2。我需要首先检查ticketType是否存在以及是否未定义,然后需要确定它是1还是2。
下面的if语句生成一个错误:
if(typeof ticketType != undefined && ticketType == 1){}上面写的是ticketType isn't defined。我尝试嵌套if语句,以检查它是否已定义,我认为它不会尝试内部的if语句,但firebug仍然会生成错误。
有什么想法吗?一定有办法做到这一点的……
发布于 2011-11-18 05:51:47
与typeof一起使用时,'undefined'需要用引号括起来
if(typeof ticketType != 'undefined' && ticketType == 1){}发布于 2011-11-18 05:53:58
未定义应包含在引号内...
if (typeof ticketType !== "undefined" && ticketType == 1)
{
}编辑
这里我们不是在讨论global.undefined,它不需要用引号括起来。我们讨论的是typeof operator的返回类型,它是一个字符串。顺便说一句,对于未定义的变量,typeof返回" undefined“,因此我们需要将它包含在string中。
// ticketType is not defined yet
(typeof ticketType !== undefined) // This is true
(typeof ticketType === undefined) // This is false
(typeof ticketType !== "undefined") // This is false
(typeof ticketType === "undefined") // This is true
var ticketType = "someValue"; // ticketType is defined
(typeof ticketType !== undefined) // This is still true
(typeof ticketType === undefined) // This is still false
(typeof ticketType !== "undefined") // This is true
(typeof ticketType === "undefined") // This is false因此,正确的检查是针对"undefined"而不是针对global.undefined。
发布于 2011-11-18 05:52:40
if(typeof ticketType != 'undefined' && ticketType == 1){}我认为你需要在未定义的单词周围加上引号。至少我总是这样做。
https://stackoverflow.com/questions/8174844
复制相似问题