简体   繁体   中英

how to check if an object exists in javascript

I want to check if the window.sessionStorage object exists. Is this the way to do it:

if (window.sessionStorage)

in javascript?

if(sessionStorage.length == 0) {
    //do something
}

That will validate whether sessionStorage is empty or not. Alternatively, you can use this:

if(typeof(sessionStorage) == 'undefined')  {
    //do something
}

Use can use modernizr to check session/web storage and other browser features.

In case you can't add the lib, check how they handle it here

Cheers.

Your proposed solution will work since we know that the sessionStorage property must refer to an object—and objects always resolve truthy in expressions.

However a word of caution, when checking for the existence of any arbitrary property in JavaScript (where we don't necessarily know the value), it's safest to check that the key exists in the object of interest. For example:

var exists = (someObject && 'someProp' in someObject);

We need to do this because someProp could be a valid property yet the test would fail when equal to: false , "" , 0 , or any other value that would be falsey in an expression.

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