如何在 JavaScript 物件或陣列中檢查特定鍵是否存在?


在 JavaScript 中,物件以鍵值對的形式存在。物件的鍵被稱為該物件的屬性,並用字串表示。物件的屬性可以具有任何資料型別的值。

例如,如果建立一個員工物件,則它具有員工姓名、員工 ID、員工年齡、工資等屬性。這些是員工物件的屬性,稱為鍵。這些屬性的值對於不同的員工將是不同的。

對於陣列,鍵是索引,如果存在給定的索引,則該索引處將有一個值。

可以透過使用一些函式和運算子來檢查 JavaScript 中物件或陣列中鍵的存在。

使用 in 運算子

in 運算子僅檢查物件的給定鍵,並返回布林結果,即如果物件具有給定鍵則返回“true”,否則返回“false”。

語法

in 運算子的語法如下所示。

For objects:
key in objectName //returns true if the object has the (key)objectProperty

示例

此示例演示瞭如何使用 in 運算子檢查物件中是否存在鍵。

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。

語法

For arrays:
Index in arrayName //returns true if the given index has a value

示例

此示例演示瞭如何使用 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() 函式的語法。

For object:
objectName.hasOwnPropert(key) //key is object property.

示例 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)

更新於:2022年8月26日

11K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告