checking for not null not working with localStorage

This question already has an answer here:

  • Storing Objects in HTML5 localStorage 25 answers
  • How to set localstorage item back to null. 2 answers

  • 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!');
    }
    
    链接地址: http://www.djcxy.com/p/27932.html

    上一篇: 为什么localStorage不接受我的对象?

    下一篇: 检查不为空不与localStorage一起工作