Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
HTML5本地存储和变量类型_Html_Variables_Types - Fatal编程技术网

HTML5本地存储和变量类型

HTML5本地存储和变量类型,html,variables,types,Html,Variables,Types,我只是在为HTML5的本地存储做一些测试。注意:我使用了Safari 6.0.2,因为许多web引擎处理方法似乎不同 如果我这样做: localStorage.setItem('subTotal', Number(12345)); // I know, it's redundant :) var varType = typeof localStorage.getItem('subTotal'); alert(varType); 你现在会想;这是一个数字!。但不,不是。。看起来,即使使用类型转

我只是在为HTML5的本地存储做一些测试。注意:我使用了Safari 6.0.2,因为许多web引擎处理方法似乎不同

如果我这样做:

localStorage.setItem('subTotal', Number(12345)); // I know, it's redundant :)
var varType = typeof localStorage.getItem('subTotal');

alert(varType);
你现在会想;这是一个数字!。但不,不是。。看起来,即使使用类型转换,HTML5本地存储在插入变量类型时也会将所有变量类型转换为字符串。这很有趣,因为当使用开发工具时,它会在引号之间显示字符串值,而不是数字。也许是检查器窗格删除了引用

我已经在jQuery中使用了一个旧的自动类型转换功能,但是我总是对这些情况感到厌倦,因为0和false仍然会把事情搞得一团糟


有人知道localStorage.*库是否有维护变量类型的设置吗?

您应该首先将它们转换为JSON:

localStorage.setItem( 'subTotal', JSON.stringify(12345) );
然后,在检索项目时,解析JSON:

JSON.parse( localStorage.getItem('subTotal') );
这是小提琴:


为便于使用,请创建自己的包装器:

var myLocalStorage = {
    set: function (item, value) {
        localStorage.setItem( item, JSON.stringify(value) );
    },
    get: function (item) {
        return JSON.parse( localStorage.getItem(item) );
    }
};

这里有一个问题:

本地存储将所有内容转换为字符串(因为它将所有内容保存为文本)。 为了让您的生活更轻松,并至少保留数字/布尔/对象结构,
JSON.stringify
JSON.parse
所有进出的内容


为了提高该建议的性能,每个“概念”只使用一个localStorage变量(如地图小部件的所有数据或所有用户首选项等),并构建一个JS对象,然后将其转换为JSON字符串,以保存到该变量中(必要时)。

使用,在这里,您可以透明地设置/获取以下任何“类型”:数组、布尔值、日期、浮点值、整数、Null、对象或字符串

[免责声明]我是实用程序的作者[/免责声明]

示例:

localDataStorage.set( 'key1', 'Belgian' );
localDataStorage.set( 'key2', 1200.0047 );
localDataStorage.set( 'key3', true );
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } );
localDataStorage.set( 'key5', null );

localDataStorage.get( 'key1' );   -->   'Belgian'
localDataStorage.get( 'key2' );   -->   1200.0047
localDataStorage.get( 'key3' );   -->   true
localDataStorage.get( 'key4' );   -->   Object {RSK: Array(5)}
localDataStorage.get( 'key5' );   -->   null
所有转换工作都是在后台为您完成的:只需设置并获取即可。

示例:

let id = JSON.parse(<any>localStorage.getItem("id"))
    
if (typeof id != "number") {
// rest of code
let id=JSON.parse(localStorage.getItem(“id”))
如果(id的类型!=“编号”){
//代码的其余部分