admin管理员组文章数量:1323529
Does anyone know why would this happen for below code
if(myVarible !=undefined){ myVarible.doSomething() }
myVariable is A global object that is used only on some pages I am sure I've done this in a past and it always worked. I also tried
if(!!s){}
Which I am also sure I've used in the past.
finally got it to work with if(typeof s!=="undefined"){}
but I would like to know why undefined variable is not equal to undefined
and why did it work in the past?
Thanks
Does anyone know why would this happen for below code
if(myVarible !=undefined){ myVarible.doSomething() }
myVariable is A global object that is used only on some pages I am sure I've done this in a past and it always worked. I also tried
if(!!s){}
Which I am also sure I've used in the past.
finally got it to work with if(typeof s!=="undefined"){}
but I would like to know why undefined variable is not equal to undefined
and why did it work in the past?
Thanks
Share Improve this question asked Mar 11, 2015 at 21:15 bluebyblueby 812 silver badges9 bronze badges 2-
Suggestion: what's wrong with
if (!s) {...}
? Also: look here: stackoverflow./questions/27509/… – paulsm4 Commented Mar 11, 2015 at 21:18 -
Because
undefined
can be reassigned, you should always check against the type anyway. – SeanCannon Commented Mar 11, 2015 at 21:18
2 Answers
Reset to default 6From what I understood, the problem is, that on some pages you don't create the global myVarible
variable at all.
For such case checks
myVarible !== undefined
and
typeof myVarible !== "undefined"
are not equal. The difference is, that only typeof
operator can handle non-existing references to names (e.g. variables). All other language constructs throw ReferenceError
when encountering reference that cannot be resolved. typeof
returns the string "undefined"
for this case.
So, in your case, you should use the typeof
operator or check existence of the variable
property on global object.
if (window.myVarible) {}
link to ecma-script specification defining typeof behavior
Use if(window.myVarible)
instead. If you check for the variable per se, JavaScript will try to execute or check the value of the variable1 which in turn yields this error message.
You can also use if(typeof myVarible !== "undefined")
which will only look at the type of the variable but not at its value.
1The way that JavaScript checks for the value of a variable depends on whether that variable was written as an object property like window.myVar
or without.
本文标签:
版权声明:本文标题:javascript - Uncaught ReferenceError: myVarible is not defined in if statement comparing to undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742129741a2422105.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论