如果localStorage对象为空,则删除localStorage

时间:2020-10-16 14:35:03

标签: javascript local-storage

如果我有一个像这样的localStorage对象:

  • 键:jpxun
  • 值:[{"id":"0","name":"juicy.stingy"}]

然后我可以通过以下任一路线将其删除:

  1. localStorage.clear();
  2. localStorage.removeItem('jpxun');

我有这段代码可以添加或删除localStorage项:

var lists = document.querySelectorAll('.list');

// if lists is not empty
if (lists.length) {
  lists.forEach(list => {
    list.addEventListener('click', e => {  
      if (!e.target.id) return;
      var id = e.target.id;
      var item = e.target;
      var temp = jpxun_length++;
      var newCt = "" + temp + ""; // need to wrap ID in speech marks to get delete element functionality to work
      var findme = jpxun.findIndex(e => e.name == id);
      
      // add word to localStorage
      
      if (findme == -1) {
        jpxun.push({ id: newCt, name: id });
        item.className = 'fav';
        var elem = document.getElementById('success');
        elem.removeAttribute('disabled');
        elem.removeAttribute('style');
        
      // remove word from localStorage
        
      } else {
          
        jpxun.splice(findme, 1)
        item.className = 'nofav';

        // recount elements
        var re_count = jpxun.length;
                
        if (re_count == 0) {
        
            // delete jpxun localStorage
            localStorage.clear();
        
            // if elements are empty, make the fav button inactive
            document.getElementById('success').setAttribute("disabled" , true);
            
        }
        
      }
      
      localStorage.setItem('jpxun', JSON.stringify(jpxun));
    });
  });
  
}

如果我从localStorage中删除了最后一个项目,则它看起来像这样:

  • 键:jpxun
  • 值:[]

在这种情况下,此行不会删除localStorage:

localStorage.clear();

我也尝试过删除localStorage:

localStorage.removeItem('jpxun');

如果我在浏览器控制台中输入代码,它们都可以使用,但是当在此处遇到该行时,从代码段中调用jpxun来删除localStorage项时,它们都不会删除 if (re_count == 0) { // delete jpxun localStorage localStorage.clear(); // if elements are empty, make the fav button inactive document.getElementById('success').setAttribute("disabled" , true); }

data = np.random.rand(29,43)

那是为什么,我可以解决它吗?

0 个答案:

没有答案