¿Cómo comprobar si un elemento de almacenamiento está configurado?


¿Cómo puedo comprobar si un elemento está configurado en localStorage? Actualmente estoy usando

if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}
Author: Xufox, 2010-07-16

9 answers

El getItem método en la especificación WebStorage, devuelve explícitamente null si el elemento no existe:

... Si la clave dada no existe en la lista asociada con el objeto, este método debe devolver null. ...

Así que puedes:

if (localStorage.getItem("infiniteScrollEnabled") === null) {
  //...
}

Vea esta pregunta relacionada:

 359
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:44

La forma más corta es usar el valor predeterminado, si la clave no está almacenada:

var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */
 14
Author: Vladislav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-20 12:59:43

Puede usar el método hasOwnProperty para verificar esto

> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false

Funciona en las versiones actuales de Chrome(Mac), Firefox(Mac) y Safari.

 12
Author: Stephan Hoyer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-04 11:16:02

También puede probar esto si desea comprobar si no está definido:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

GetItem es un método que devuelve null si no se encuentra valor.

 4
Author: Prime_Coder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-29 12:10:03

¿Cómo se puede probar la existencia de un objeto en localSotorage? este trabajo en Internet explorer

<script>
    try{
        localStorage.getItem("username");
    }catch(e){
        alert("we are in catch "+e.print);
    }
</script>
 2
Author: le vantard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-08 18:05:37

Para VERDADERO

localStorage.infiniteScrollEnabled = 1;

PARA FALSO

localStorage.removeItem("infiniteScrollEnabled")

COMPROBAR LA EXISTENCIA

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}
 1
Author: Derin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-22 04:33:47
if(!localStorage.hash) localStorage.hash = "thinkdj";

O

var secret =  localStorage.hash || 42;
 1
Author: Deepak Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-10 20:49:09

Debe comprobar el tipo del elemento en el localStorage

if(localStorage.token !== null) {
   // this will only work if the token is set in the localStorage
}

if(typeof localStorage.token !== 'undefined') {
  // do something with token
}

if(typeof localStorage.token === 'undefined') {
  // token doesn't exist in the localStorage, maybe set it?
}
 1
Author: webmaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-24 15:21:12
localStorage['root2']=null;

localStorage.getItem("root2") === null //false

Tal vez sea mejor hacer un escaneo del plan ?

localStorage['root1']=187;
187
'root1' in localStorage
true
 0
Author: zloctb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-26 07:35:44