简体   繁体   English

检查数组中是否存在节点

[英]Checking if a node exists in an array

I'm trying to check if a node exists in an array but can't seem to get my if statement correct. 我正在尝试检查数组中是否存在节点,但似乎无法使我的if语句正确。

I've currently got : 我目前有:

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

In some cases [14] wont exist as the array length is only 5 or 6, so want to make sure it doesn't try to do anything if [14] doesn't have any items in it. 在某些情况下,[14]不会存在,因为数组长度只有5或6,所以要确保如果[14]中没有任何项目,它不会尝试执行任何操作。

You snippet is correct, when a node doesn't exist, is undefined, but in no-strict comparation, undefined == null. 您的代码片段是正确的,当一个节点不存在时,它是未定义的,但在严格比较中,未定义== null。 If a node doesn't exist, will show a error. 如果一个节点不存在,将显示错误。 if you use typeof, this will cover if all nodes is valid. 如果使用typeof,它将覆盖所有节点是否有效。

Example

// ["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") { 

}

If the array length is only 5 or 6, then it means element 14 won't even exist, you should be checking for undefined not null: 如果数组长度只有5或6,则意味着元素14甚至都不存在,您应该检查undefined而不是null:

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

or: 要么:

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

or even: 甚至:

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

I would recommend an option but it really comes down to preference and I'd rather not incite a style/best practice war :) Just pick whichever you prefer. 我会推荐一个选项,但是它实际上取决于偏好,我宁愿不煽动风格/最佳实践之战:)随便选一个。

Here's a thorough explanation on the difference between null and undefined , but essentially null means the value is null , whereas undefined means the variable has not been declared. 这是对null和undefined之间区别的详尽解释 ,但是本质上null表示值是null ,而undefined表示变量尚未声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM