javascript 如何检查javascript数组中是否存在键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34132168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a key exists in javascript array?
提问by Dilip Kumar Yadav
How can i check if a particular key exists in a JavaScript array?
如何检查 JavaScript 数组中是否存在特定键?
Actually, i am checking for undefinedness for whether a key exists. What if the key exists but the value is actually undefined?
实际上,我正在检查密钥是否存在的不确定性。如果键存在但值实际上未定义怎么办?
var obj = { key: undefined }; obj["key"] != undefined // false, but the key exists!
var obj = { key: undefined }; obj["key"] != undefined // 错误,但键存在!
回答by Nina Scholz
回答by Quentin
回答by cohen chaim
Use hasOwnProperty(key)
使用 hasOwnProperty(key)
for (let i = 0; i < array.length; i++) {
let a = obj[i].hasOwnProperty(`${key}`);
if(a){
console.log(obj[i])
}
}