简体   繁体   中英

Javascript: check for key in array that might not exist

Say boundEvents is an array that might or might not exist. If it doesn't exist, then the following code will return 'undefined':

console.log(typeof boundEvents);

Fine. That is exactly what I want. Now say I want to check that theoretical array for the existence of a key which might or might not exist.

console.log(typeof boundEvents['click']);

Uh oh:

Uncaught TypeError: Cannot read property 'click' of undefined

Fair enough, javascript. So let's check to see if the array exists, before we check for the key:

if(typeof boundEvents != 'undefined'){
    console.log(typeof boundEvents['click']);
}

Working again, but I'm wondering if there is a way to eliminate the if statement and just check on the existence of boundEvents['click'] directly, in one step?

Thanks!

EDIT: complete answer, combined from below:

var boundEvents = boundEvents || {};   
console.log(boundEvents.hasOwnProperty('click'));

You can do:

boundEvents = boundEvents || {};
console.log(boundEvents['click']);

or in a single line:

console.log((boundEvents || {})['click']);

如果您想要明确的true / false则:

(boundEvents || {}).hasOwnProperty('click')

You can check each layer ending on the variable you want. This will default to undefined if everything is false.

( (typeof boundEvents !== "undefined") && boundEvents['click']) || undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM