如何将localStorage值设置为false?

时间:2016-05-18 17:36:18

标签: javascript boolean local-storage

我想将false添加到localStorage['flag'] = false我尝试过:

localStorage['flag'] = false;
localStorage['flag'] = 0;

但是当我检查时

if(!localStorage['flag']){
  //this will never happen
}
/**or**/
if(localStorage['flag']){
  //this will happen always
}

小提琴示例:https://jsfiddle.net/qqew0zzf/

1 个答案:

答案 0 :(得分:4)

您可以使用setItemgetItem来存储您的旗帜。请记住,在使用getItem后,这将使您“错误”回来,这是您原始尝试失败的原因(字符串'false'不是假值)。通常使用JSON来保存和检索本地存储中的对象。

localStorage.setItem('flag', false);
var flag = localStorage.getItem('flag');
//flag is "false"

使用JSON:

localStorage.setItem('flag', JSON.stringify(false));
var flag = JSON.parse(localStorage.getItem('flag'));
//flag is the boolean false