簡體   English   中英

檢查jQuery / Javascript是否未定義

[英]Checking if undefined in jQuery/Javascript

我有以下幾點:

var currentQuestion = $(this).closest(".question")

我已經嘗試過在這個這個這個問題中建議的所有內容:

if(currentQuestion !== undefined)
if(currentQuestion !== "undefined")
if(typeof currentQuestion !== undefined)
if(typeof currentQuestion !== "undefined")
if(currentQuestion !== null)
if(currentQuestion != undefined)
if(currentQuestion != "undefined")
if(currentQuestion.data("index") !== null)
if(currentQuestion.data("index") !== undefined)
if(typeof currentQuestion.data("index") !== undefined)

但是它一直在if語句里面...

我在if里面有這個:

console.log("nextQ: " + currentQuestion.data("index"));

nextQ: undefined正在被打印出來

還有其他想法嗎?

編輯:

currentQuestion.data("index") != null

解決了。 如果您檢查了我之前嘗試過的所有選項,則與此類似的選項具有以下比較元素: !==而不是!= 這種變化帶來了不同。 如果有人可以解釋原因,我會給他/她正確的答案。

結果永遠不會是不確定的,它始終是jQuery對象。 如果該操作未找到任何元素,則jQuery對象將為空,因此您檢查其中有多少個元素以查看是否找到了任何東西:

if (currentQuestion.length > 0)

檢查jQuery對象中實際上是否有任何元素之后,可以檢查是否有任何與該元素相關聯的數據。

如果沒有數據與元素關聯,則當您嘗試讀取值時, data方法將返回undefined 因此,要檢查是否沒有數據,應檢查data方法返回的值的類型:

if (typeof currentQuestion.data("index") != "undefined")

您想要的是currentQuestion.length

jQuery選擇器返回與選擇器匹配的元素數組。 要測試數組中的值,應使用length

Boolean([].length); //false

由於0的計算結果為false,因此可以只使用if (currentQuestion.length)

如果您嘗試檢查它是否為假,請使用!

if (!currentQuestion.length)

對於為什么!=起作用但!==無效的問題,我建議以下問題: JavaScript中==和===之間的區別

基本上, currentQuestion.data('index')並不嚴格等於null ,但是它可以評估為null :與[] == 0評估為true ,但是[] === 0評估為false

如果要檢查是否存在任何元素,請檢查長度。

var currentQuestion = $(this).closest(".question");
if (currentQuestion.length > 0) {
    console.log("nextQ: " + currentQuestion.data("index"));
}
if (currentQuestion.length) {

應該工作正常。 如果它進入那里,它發現了一些東西。 而不是查看if語句,您需要查看html並查看所找到的內容。

這可能不是最優雅的解決方案。 但是不知何故

currentQuestion.data("index") != null

解決了。 如果您檢查了我之前嘗試過的所有選項,則與此最類似的選項具有以下比較元素: !==而不是!= 這種變化帶來了不同。 如果有人可以解釋原因,我會給他/她正確的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM