如何檢查 JavaScript 對象/數組中是否存在鍵
簡介
JavaScript 中的對像是 key-value 的無序集合 對(key: value
)。每個鍵 被稱為屬性 ,並且是表示屬性名稱的字符串。如果給定一個非字符串作為鍵,則將使用它的字符串化表示。屬性的值 可以是概念上適合該屬性的任何數據類型——字符串、數字、數組,甚至是函數。
另一方面,數組是一組已排序的值。每個值稱為一個元素,由數字索引標識。數組可以包含幾乎任何類型的值。例如,它可以存儲整數、字符串、布爾值、函數等項目。JavaScript 數組也不限於單一類型,這意味著給定的數組可以包含多種不同的類型。
在 JavaScript 中工作時,您可能在特定時間點需要確定給定對像或數組中是否存在鍵。
使用in
運算符
in
JavaScript 中的運算符用於確定某個屬性是否存在於對像或其繼承的屬性(也稱為其原型鏈)中。如果提供的屬性存在,in
運算符返回 true。
檢查對象
let user = {
name: 'John Doe',
age: 17,
profession: 'Farmer'
};
// Check if key exists
'name' in user; // Returns true
'profession' in user; // Returns true
'Daniel' in user; // Returns false becuase no key like that exists
'Farmer' in user; // Returns false because 'Farmer' is not a key, but a value
檢查數組
由於我們演示了 JavaScript in
運算符可以與對像一起使用,您可能會問它是否也可以與數組一起使用。在 JavaScript 中,一切都是 Object 類型的實例(除了原語),因此數組也支持 in
運營商。
讓我們確認它是否是 Object
的實例 使用 instanceof
鍵入 運營商:
let numbers = [22, 3, 74, 35];
numbers instanceof Object // Returns true
現在,回到使用 in
運營商:
let numbers = [12, 33, 14, 45, 6];
// Checking if index 1 is present
1 in numbers; // Returns true
// Checking if index 3 is present
3 in numbers; // Returns true
8 in numbers; // Returns false because the 8 index does exist in the array
6 in numbers; // Returns false because the 6 index does not exist in the array
這也將返回 true
用於數組類型的方法屬性,其中數字數組是一個實例。
'map' in number; // Returns true because 'map' is a method attribute of the array type
使用hasOwnProperty()
方法
在 JavaScript 中,hasOwnProperty()
函數用於確定對像是否將提供的屬性作為自己的屬性。這對於確定屬性是否被對象繼承而不是自己的屬性很重要。
檢查對象
let user = {
name: 'John Doe',
age: 17,
profession: 'Farmer'
};
// Check if key exists
let hasKey = user.hasOwnProperty('name');
if (hasKey) {
console.log('This key exists.');
} else {
console.log('This key does not exist.');
}
檢查數組
您可能會開始懷疑這是否適用於數組。正如我們之前建立的,數組實際上是Object
的原型(實例) 類型,因此它也有這個方法可用。
let number = [12, 33, 14, 45];
// Check if key exists
number.hasOwnProperty(1); // Returns true
number.hasOwnProperty(0); // Returns true
number.hasOwnProperty(7); // Returns false because 7 is not an existing index on the array
使用Object.key()
方法
靜態方法 Object.key
生成並返回一個數組,其組件是對象屬性的名稱(鍵)字符串。這可以用來循環遍歷對象的鍵,然後我們可以使用它來驗證是否有任何匹配對像中的某個鍵。
使用some()
方法
some()
是一個 JavaScript 方法,它在調用數組的所有元素上測試回調函數並返回 true
如果回調函數返回 true
對於任何 其中。
使用 some()
對象
let user = {
name: 'John Doe',
age: 17,
profession: 'Farmer'
};
// Check if key exists
Object.keys(user).some(key => key === 'name'); // Returns true
Object.keys(user).some(key => key === 'role'); // Returns false
我們還可以將其自定義為可重用的函數:
const checkKey = (obj, keyName) => {
let keyExist = Object.keys(obj).some(key => key === keyName);
console.log(keyExist);
};
checkKey(user, 'name'); // Return true
使用 some()
對於一個數組
let number = [12, 33, 14, 45];
// Check if key exists
number.some(value => value === 1); // Returns true
number.some(value => value === 7); // Returns false
同樣,就像對像一樣,我們也可以使用類似的自定義可重用函數來檢查數組中值的存在:
const checkVal = (arr, val) => {
let valExist = arr.some(value => value === val);
console.log(valExist);
};
checkVal(number, 7); // Returns false
checkVal(number, 0); // Returns true
使用indexOf()
方法
JavaScript 的 indexOf()
方法將返回 第一個實例的索引 數組中的一個元素。如果元素不存在則返回-1。
使用 indexOf()
對於一個對象
Object
type in JavaScript 實際上並不支持 indexOf
方法,因為它的屬性/鍵本身在對像中沒有索引位置。相反,我們可以將對象的鍵作為數組獲取,然後使用 indexOf
檢查鍵是否存在 方法:
免費電子書:Git Essentials
查看我們的 Git 學習實踐指南,其中包含最佳實踐、行業認可的標準以及隨附的備忘單。停止谷歌搜索 Git 命令並真正學習 它!
let user = {
name: 'John Doe',
age: 17,
profession: 'Farmer'
};
// Check if key exists
Object.keys(user).indexOf('name') // Returns 0
Object.keys(user).indexOf('role') // Returns -1
請記住,JavaScript 對象並不總是保持鍵順序 ,因此返回的索引可能不像數組中那樣有意義。在這種情況下,索引應該主要用於確定鍵是否存在。
以下是在實用函數中使用 this 的示例:
const checkKey = (obj, keyName) => {
if (Object.keys(obj).indexOf(keyName) !== -1) {
console.log('This key exists');
} else {
console.log('This key does not exist');
}
};
checkKey(user, 'name'); // Logs 'This key exists'
checkKey(user, 'role'); // Logs 'This key does not exists'
使用 indexOf()
對於一個數組
正如我們在前面的示例中看到的,數組確實支持 indexOf
方法,不像對象。要使用它,請將您要查找的項目的值傳遞給 indexOf
,如果它存在於數組中,它將返回該值的位置:
let number = [12, 33, 14, 45];
// Find position of the item in the array
number.indexOf(14); // Returns 2
number.indexOf(7); // Returns -1
結論
在本文中,我們看到了檢查 JavaScript 對象/數組中是否存在鍵或項的所有可能方法。我們展示瞭如何使用 in
運算符,hasOwnProperty()
方法和 some
方法。我們還看到了 JS 對象和數組是如何相似的,因為數組繼承自對象,因此包含許多相同的方法。