【问题标题】:localStorage and boolean 'string'localStorage 和布尔“字符串”
【发布时间】:2015-08-19 02:08:03
【问题描述】:

在localStorage中存储布尔值,这个值被转换为字符串。 现在尝试将此值从 localStorage 转换回布尔值,我需要使用JSON.parse() 方法,更方便的!! 不起作用。

代码示例:

var test = false;
localStorage['test'] = test;
console.log("JSON.parse returns: ", JSON.parse(localStorage['test']), "expected: ", test);
console.log("'!!' returns: ", !! localStorage['test'], "expected: ", test);

-jsFiddle-

我很困惑为什么会出现这种行为。有什么解释吗?

PS:在这里使用 getter/setter localStorage 方法无关紧要,结果相同。

【问题讨论】:

标签: javascript html boolean local-storage


【解决方案1】:

本地存储存储字符串,恐怕,无论输入是什么(如果你用一个对象提供它,它将使用其标准 toString() 方法自动转换)......所以你在做 !! test一个字符串,总是true

在处理存储在DOM storage 中的内容时,您应该始终使用JSON.stringify()JSON.parse()

【讨论】:

    【解决方案2】:

    使用 JSON.stringify() 保存对象时。如您所知,它会将 JavaScript 值转换为 JSON 字符串,因此在使用 JSON.parse() 时,它会正确转换回来。

    localStorage['test'] = JSON.stringify(test);
    

    DEMO

    【讨论】:

      【解决方案3】:

      发生这种情况是因为本地存储中的任何存储值都是字符串。 因此,对于非空字符串,您执行 !!"false"!! 始终为 true。 为了能够在 localStorage 中存储非字符串值,您必须始终使用 JSON。

      【讨论】:

        【解决方案4】:

        你想要做的很简单localDataStorage,你可以透明地设置/获取以下任何“类型”:数组、布尔、日期、浮点数、整数、空值、对象或字符串。

        [DISCLAIMER] 我是该实用程序的作者 [/DISCLAIMER]

        例子:

        localDataStorage.set( 'test', false );
        
        localDataStorage.get( 'test' );   -->   false
        

        所有转换工作都在后台为您完成:只需设置/获取即可。

        【讨论】:

          猜你喜欢
          • 2013-06-13
          • 2013-11-28
          • 2011-04-23
          • 2015-02-07
          • 2014-03-30
          • 2015-02-24
          • 2016-07-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多