Home >Web Front-end >JS Tutorial >How Can I Reliably Check for Key Existence in JavaScript Objects and Arrays?
Question:
How can I reliably check if a specific key exists within a JavaScript object or array?
Concerns:
Answer:
Checking for key existence using the undefined operator is not recommended because it can be unreliable. Consider the following scenario:
var obj = { key: undefined }; console.log(obj["key"] !== undefined); // false, but the key exists!
In this case, the key "key" exists in the object obj, but its value is undefined. Therefore, checking if obj["key"] is not undefined returns false.
Recommendation:
To reliably check for key existence, use the hasOwnProperty() method for objects and the in operator for arrays and objects:
The above is the detailed content of How Can I Reliably Check for Key Existence in JavaScript Objects and Arrays?. For more information, please follow other related articles on the PHP Chinese website!