最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Checking to see if a value exists in Javascript - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 10

Use 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.

发布评论

评论列表(0)

  1. 暂无评论