如何检查特定键是否存在于 javascript 对象或数组中?
在 JavaScript 中,对象以键值对的形式存在。对象的键称为给定对象的属性,并使用字符串表示。对象的属性可以具有任何数据类型的值。
例如,如果创建了一个员工对象,则它具有员工姓名、员工 ID、员工年龄、薪水等属性。这些是员工对象的属性,称为键。对于不同的员工,这些属性的值会有所不同。
对于数组,键是索引,如果给定的索引存在,则索引处会有一个值。
可以使用一些函数和运算符来检查 JavaScript 中对象或数组的键是否存在。
使用 in 运算符
in 运算符仅检查对象的给定键,并返回布尔结果,即,如果对象具有给定的键,则返回"true",否则返回"false"。
语法
in 运算符的语法如下所示。
对于对象: key in objectName //如果对象具有 (key)objectProperty,则返回 true
示例
此示例演示了如何使用 in 运算符来检查对象中是否存在 key −
let employee = { firstName: 'Mohammed', lastName: 'Abdul Rawoof', id : 1000, designation: 'Intern Software Engineer', salary : 18000 }; console.log("The given employee details are: ",employee) console.log("Is firstName present in employee:",'firstName' in employee); console.log("Is employee age present in employee:",'age' in employee) console.log("Is 18000 present in employee:", 18000 in employee)
数组的 in 运算符
在数组中,如果给定索引处存在值,则 in 运算符将返回 true,否则返回 false。
语法
对于数组: Index in arrayName //如果给定的索引有值,则返回 true
示例
此示例演示如何使用 in 运算符检查数组中是否存在键 -
function getKeyArr(a,indx){ console.log("The given array with its length is:",a,a.length) if(indx in a){ console.log("The array has a key at the given index",indx) } else{ console.log("The array doesn't have a key at the given index",indx," as its array length is:",a.length) } } console.log("Checking the existance of a key in an array using hasOwnProperty()") getKeyArr([12,56,33,2,7],4) getKeyArr([12,56,33,2,7],8) getKeyArr([1,2,4,53,36,7,83,90,45,28,19],16)
使用 hasOwnProperty() 函数
函数 hasOwnProperty() 将检查给定对象中是否存在键,如果键存在则返回 true,否则返回 false。此函数将对象的键作为参数,并相应地返回布尔结果。
语法
这是 hasOwnProperty() 函数的语法。
对于对象: objectName.hasOwnPropert(key) //key 是对象属性。
示例 3
此示例演示了如何使用 hasOwnProperty() 检查对象中的键 -
let employee = { emp_name: 'Abdul Rawoof', emp_id: 1000, role: 'Software Engineer', salary: 18000 }; console.log("The given employee details are:", employee) console.log("Checking the keys present in an object using hasOwnProperty:") function getEmpDet(str){ if(employee.hasOwnProperty(str)){ console.log("The given employee object has",str) } else{ console.log("The given employee object doesn't have",str) } } getEmpDet('emp_id') getEmpDet('salary') getEmpDet('designation')
数组的 hasOwnProperty()
在数组中,如果给定索引处存在值,则 in 运算符将返回 true,否则返回 false。而 hasOwnProperty() 方法可以检查索引是否可用但不为空。
语法
数组的 hasOwnProperty() 语法如下所示。
arrayName.hasOwnProperty(index)
示例
此示例演示如何使用 hasOwnProperty 检查数组中是否存在键 -
function getKeyArr(a,indx){ console.log("The given array with its length is:",a,a.length) if(a.hasOwnProperty(indx)){ console.log("The array has a key at the given index",indx) } else{ console.log("The array doesn't have a key at the given index",indx," as its array length is:",a.length) } } console.log("Checking the existance of a key in an array using hasOwnProperty()") getKeyArr([12,56,33,2,7],4) getKeyArr([12,56,33,2,7],8) getKeyArr([1,2,4,53,36,7,83,90,45,28,19],16)