当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - checking for not null not working with localStorage

问题描述:

This question already has an answer here:

  • Storing Objects in HTML5 localStorage

    24 answers

  • How to set localstorage item back to null.

    1 answer

网友答案:

According to this answer:
Storing Objects in HTML5 localStorage

localStorage is made to save String key-value-pairs, only!

null is an empty Object.

So this is not a bug, it is actually the expected behaviour.

网友答案:

You can only store string in the localStorage.

So, when you save null value in localStorage, you're actually storing "null"(string) in the localStorage.

To check if value in localStorage is null, use ==.

Example:

localStorage.setItem('foo', null);
console.log(localStorage.getItem('foo')); //logs null as string
console.log(typeof localStorage.getItem('foo')); //logs string

if (localStorage.getItem('foo') != null) {
//                              ^^         // Don't use strict comparison operator here
    console.log('Should work now!');
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: