2012-07-05 50 views
0

我在jQuery代碼中有兩個變量,如果item.a不存在,它會輸出'null',所以我想檢查變量是否存在。下面的代碼:如何檢查jquery中是否存在變量

.append("<a>" + item.a + ", " + item.b + "</a>") 

如果沒有 「item.a」 它導致

null, Blabla 

我想這if/else語句,但是它沒有返回

.append("<a>" + (item.a) ? item.a : + ", " + item.b + "</a>") 

任何想法?

+0

使用原生的JavaScript,請參閱:http://stackoverflow.com/questions/2703102/typeof-undefined-vs-null瞭解更多詳細信息。 – StuperUser 2012-07-05 11:01:25

+1

嚴格地說,你不需要一個_existence_檢查 - 如果值爲null,你需要一個_falsey_檢查。 – Alnitak 2012-07-05 11:07:06

回答

5

你的嘗試很接近。試試這個:

.append("<a>" + (item.a ? item.a : "") + ", " + item.b + "</a>") 

或者,假設你不希望逗號,當您沒有item.a信息:

.append("<a>" + (item.a ? item.a + ", " : "") + item.b + "</a>") 
+0

我懷疑他不想要逗號,如果只有一個項目... – Alnitak 2012-07-05 11:00:48

+0

@Alnitak - 是的,可能。我已經添加了。 – 2012-07-05 11:02:06

+0

這工作。謝謝。 – Adige72 2012-07-05 11:14:36

1

使用條件運算符

編輯

.append("<a>" + (item.a != null ? item.a + ", " : "") + item.b + "</a>") 

如果變量爲空

if(varName === null) 
{ 
    alert("variable has null"); 
} 

如果變量不存在

if(typeof varName === 'undefined') 
{ 
    alert("variable not defined"); 
} 
+0

變量不是'undefined';它是'null',所以你的代碼將無法工作。 – Bojangles 2012-07-05 11:01:56

+0

你應該使用三重等於:http://stackoverflow.com/questions/8044750/javascript-performance-difference-between-double-equals-and-triple-equals – StuperUser 2012-07-05 11:04:27

相關問題