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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:17:00  来源:igfitidea点击:

How to check if a key exists in javascript array?

javascript

提问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

With inoperator.

in操作员。

0 in [10, 42] // true
2 in [10, 42] // false

'a' in { a: 'foo' } // true
'b' in { a: 'foo' } // false

回答by Quentin

Use the inoperator.

使用in运营商

if ( "my property name" in myObject )

回答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])
       }
    }