簡體   English   中英

檢查數組中是否存在節點

[英]Checking if a node exists in an array

我正在嘗試檢查數組中是否存在節點,但似乎無法使我的if語句正確。

我目前有:

if (obj2["spec"]["3"]["spec2"]["14"] != null) { do stuff }

在某些情況下,[14]不會存在,因為數組長度只有5或6,所以要確保如果[14]中沒有任何項目,它不會嘗試執行任何操作。

您的代碼片段是正確的,當一個節點不存在時,它是未定義的,但在嚴格比較中,未定義== null。 如果一個節點不存在,將顯示錯誤。 如果使用typeof,它將覆蓋所有節點是否有效。

// ["spec2"] is undefined, this case will show a error.
if(array["spec"]["3"]["spec2"]["14"] != undefined) { 

}

// This doesn't he show error, if "specs2" is undefined.
if(typeof array["spec"]["3"]["spec2"]["14"] !== "undefined") { 

}

如果數組長度只有5或6,則意味着元素14甚至都不存在,您應該檢查undefined而不是null:

if(typeof array["spec"]["3"]["spec2"]["14"] !== "undefined")

要么:

if(array["spec"]["3"]["spec2"]["14"] !== undefined)

甚至:

if(!array["spec"]["3"]["spec2"]["14"])

我會推薦一個選項,但是它實際上取決於偏好,我寧願不煽動風格/最佳實踐之戰:)隨便選一個。

這是對null和undefined之間區別的詳盡解釋 ,但是本質上null表示值是null ,而undefined表示變量尚未聲明。

暫無
暫無

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

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