[英]How to check if a key exists in javascript array?
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 }; var obj = {键:未定义}; obj["key"],= undefined // false, but the key exists!
obj["key"],= undefined // false,但是键存在!
使用in
运算符。
if ( "my property name" in myObject )
let $arr = [1, 0, false];
console.log($arr.indexOf(0)); // 1
console.log($arr.indexOf(false)); // 2
console.log($arr.indexOf(15)); // -1
if ($arr.indexOf(18) !== -1) //Todo
You can use the Javascript array filter funtion.您可以使用 Javascript 阵列滤波器功能。 Like that:
像那样:
const arr = ["ab","cd"] const needle = "cd" console.log( arr.filter(i => i == needle).length > 0? "exists": "not exists" )
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])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.