我正在尝试在本地存储中切换true / false变量。
console.log("Toggling...");
console.log("Current:" + localStorage.item);
console.log("Current is being changed to: " + !localStorage.item);
localStorage.item = !localStorage.item;
console.log("Current " + localStorage.item);
这是什么?
首次运行
Toggling...
(index):31 Current:undefined
(index):32 Current is being changed to: true
(index):34 Current true
第二次运行
Toggling...
(index):31 Current:true
(index):32 Current is being changed to: false
(index):34 Current false
后续运行...
Toggling...
(index):31 Current:false
(index):32 Current is being changed to: false
(index):34 Current false
为什么我的变量没有变回true?
答案 0 :(得分:2)
实际上,您的布尔值会作为字符串存储在localStorage上。
localStorage.item类型将返回“字符串”
> localStorage.item
undefined
> localStorage.item = !localStorage.item
> localStorage.item
"true"
> localStorage.item = !localStorage.item
> localStorage.item
"false"
> localStorage.item = !localStorage.item
> localStorage.item
"false"
从这一点开始,具有 length> 0 的字符串被认为是真实的,即使其值设置为"false"
。
如果您使用recommended syntax,也会发生这种情况:
> localStorage.set('item', true);
> localStorage.get('item');
"true"
考虑:
localStorage.item =!JSON.parse(localStorage.item)
有关其他信息,请检查https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111
答案 1 :(得分:0)
您不想像这样直接在localStorage
上设置属性。而是使用setItem(key, value)
,getItem(key)
和removeItem(key)
。
docs中的示例:
以下代码段访问当前域的本地存储对象,并使用Storage.setItem()向其添加数据项。
localStorage.setItem('myCat', 'Tom');
读取localStorage项的语法如下:
var cat = localStorage.getItem('myCat');
删除localStorage项的语法如下:
localStorage.removeItem('myCat');
所以类似这样:
console.log("Toggling...");
console.log("Current:" + localStorage.getItem('item'));
console.log("Current is being changed to: " + !localStorage.getItem('item'));
localStorage.setItem('item', !localStorage.getItem('item'));
console.log("Current " + localStorage.getItem('item'));
答案 2 :(得分:0)
您可以使用JSON.parse()将其解析为布尔值:
console.log("Toggling...");
console.log("Current:" + localStorage.item);
console.log("Current is being changed to: " + !JSON.parse(localStorage.item));
localStorage.item = !JSON.parse(localStorage.item);
console.log("Current " + localStorage.item);