How to have a statement identify an undefined variable?
This question already has an answer here:
> exponent != 'undefined'
You need to understand the Abstract Equality Comparison Algorithm. The above attempts to compare the value of exponent
with the string "undefined". Since exponent
is defined but has not been assigned a value, it will return the value undefined
which is not equal to the string "undefined" (according to the algorithm above).
So you can compare its value to the undefined value:
exponent != undefined
or you can compare the type of the value with an appropriate string value using the typeof
operator (since it always returns a string):
if (typeof exponent != 'undefined')
Whether you use the strict or abstract versions above ( !==
or !=
respectively) doesn't make any difference in this case.
上一篇: 检查对象属性的首选方法是`null`或`undefined`
下一篇: 如何声明一个未定义的变量?