admin管理员组文章数量:1356585
How do I prevent a Javascript alert from firing if the alert value is undefined? In other words, something like this:
if (alert(message) != 'undefined') {
alert(message);
}
How do I prevent a Javascript alert from firing if the alert value is undefined? In other words, something like this:
if (alert(message) != 'undefined') {
alert(message);
}
Share
Improve this question
asked Dec 21, 2010 at 23:49
sehummelsehummel
5,56825 gold badges92 silver badges141 bronze badges
1 Answer
Reset to default 10Use typeof
:
if (typeof message !== 'undefined')
Don't put alert(message)
into the if
expression, otherwise you will execute alert
(which we want to avoid before we know the type of message
) and the return value (which is also undefined
btw ;)) will be pared to undefined
.
Update Clarification for !==
:
This operator not only pares the value of two operands but also the type. That means no type coercion is done:
42 == "42" // true
42 === "42" // false
In this case it is not really necessary because we know that typeof
always returns a string but it is good practice and if you use it thoroughly and consistently, it is more clear where you really want to have type coercion and where not.
本文标签: jqueryChecking to see if a value exists in JavascriptStack Overflow
版权声明:本文标题:jquery - Checking to see if a value exists in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744007260a2574924.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论