If语句条件检查!=“undefined”失败

时间:2011-12-02 13:28:30

标签: javascript jquery undefined

我正在尝试为google maps infowindow生成一些HTML内容。如果它们不等于null,undefined或“”(空字符串),我有7个值应该显示。

但显然,当if(e.Property != null || e.Property != "undefined" || e.Property == "")Property时,我的undefined无效。大多数情况下,e.Email未定义。因此,我的代码不会跳过该部分,而是插入html + "<br />部分。当我alert() e.Email它返回undefined它应该捕获并跳过,如果是这种情况。

我尝试过编写if(typeof e.Property != null || typeof e.Property != "undefined" || typeof e.Property == ""),但这没有任何区别。

// 'e ' is JSON object
var generateHTML = {
    init: function(e) {
        if (e != null || e != "undefined"){
            generateHTML.check(e);
        }
    },
    check: function (e) {
        if(e.Title != null || e.Title != "undefined" || e.Title == ""){
            html = html + "<b>"+e.Title+"</b>";
        }
        if(e.Address != null || e.Address != "undefined" || e.Address == ""){
            html = html +"<br />"+ e.Address;
        }
        if(e.Zipcode != null || e.Zipcode != "undefined" || e.Zipcode == ""){
            html = html +"<br />"+ e.Zipcode+", ";
        }
        if(e.City != null || e.City != "undefined" || e.City == ""){
            html = html + e.City;
        }
        if(e.Phone != null || e.Phone != "undefined" || e.Phone == ""){
            html = html +"<br />"+ e.Phone;
        }
        if(e.Email != null || e.Email != "undefined" || e.Email == ""){
            html = html +"<br />"+ e.Email;
        }
        if(e.WebAddress != null || e.WebAddress != "undefined" || e.WebAddress == ""){
            html = html +"<br />"+ e.WebAddress;
        }
        return html;
    }
};

7 个答案:

答案 0 :(得分:5)

您要查看!== undefined

e.g。

if(myvar !== undefined) { 
    //DO SOMETHING 
}

答案 1 :(得分:3)

if(e) //this would be shorter

if(e != undefined)
//
if(typeof(e) != 'undefined')

答案 2 :(得分:2)

如果您想要更简便的版本,可以使用:

if (e.Title) {
    // add to HTML
}
if (e.Address) {
    // add to HTML
}

您可能需要考虑将HTML构建为数组,然后在最后加入以避免创建许多字符串,例如。

var html = [];
html.push("FirstName");
html.push("<br />");
html.push("LastName");
html.push("<br />");
html.push("Number");
var output = html.join(""); // "FirstName<br />LastName<br />Number"

答案 3 :(得分:1)

undefined是变量名,不是字符串。

你不需要它周围的引号。

答案 4 :(得分:1)

您正在检查它,好像它的值是字符串“undefined”

删除“”

答案 5 :(得分:0)

通过e.length更好地检查某些内容,因为JavaScript中的变量类型不准确

答案 6 :(得分:0)

我也会使用长度函数,如果数组或对象为空,则记录长度为0.0,即

&#13;
&#13;
if(e.length == 0){
  //then do something or nothing
}
else {
  //Do somthing
}
&#13;
&#13;
&#13;

相关问题