2011-12-02 2 views
7

Google지도 정보 창에 대해 일부 HTML 콘텐츠를 생성하려고합니다. null, undefined 또는 ""(빈 문자열)과 같지 않으면 표시해야하는 7 개의 값이 있습니다.! = "undefined"인 If 문 조건 검사가 실패합니다.

Propertyundefined 일 때 내 if(e.Property != null || e.Property != "undefined" || e.Property == "")이 작동하지 않는 것 같습니다. 대부분의 경우 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; 
    } 
}; 
+2

가 왜 문자열로'undefined' 배치해야합니까 자바 스크립트에 애큐 리트하지? – Jon

+0

[자바 스크립트에서 정의되지 않은 것을 확인하는 방법?] (http://stackoverflow.com/questions/2985771/how-to-check-for-undefined-in-javascript) – Dennis

+0

+1 좋은 질문 –

답변

2

방금 ​​사용할 수있는"제거 문자열 "정의되지 않은"경우로 확인된다 HTML을 Array로 작성한 다음 끝에 여러 문자열을 만드는 것을 피하기 위해 합류하는 것이 좋습니다. e.length 원인 변수 형식을 통해

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" 
5

당신은 확인하고 싶다! ==

을 정의되지 않은 예를 들어,

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

정말 도움이 –

1

undefined은 문자열이 아니라 변수 이름입니다.

주위에 따옴표가 필요하지 않습니다.

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

당신은 할 수있다 :

+0

downvotes에 대한 이유가 무엇입니까? –

1

당신은 그 값이

당신이 더 속기 버전을 원하는 경우 "

3
if(e) //this would be shorter 

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

더 나은 체크 뭔가