For anyone interested, I ended up building a "localstorage with expirations" script here, http://plugins.jquery.com/project/localcache

对于任何有兴趣的人,我最终在这里构建了一个“带有expirations的localstorage”脚本,http://plugins.jquery.com/project/localcache

What I'm doing: building an extension for Storage, so that the user can do this:

我在做什么:构建存储扩展,以便用户可以这样做:

localStorage.setThing(key, value)

and the user can do the following:

用户可以执行以下操作:

localStorage.setThing("key1", 1)
localStorage.setThing("key2", "this is a string")
localStorage.setThing("key3", { prop1: "this is a json obj" })

In my setThing method, I'm checking for the typeof for value, and if typeof value == "object", I'm storing it as localStorage.setItem(key, JSON.stringify(value))

在我的setThing方法中,我正在检查typeof for value,如果typeof value ==“object”,我将它存储为localStorage.setItem(key,JSON.stringify(value))

On the getThing method, I know that the value that makes it into localStorage is always going to be a string. So, how can I do this?

在getThing方法中,我知道进入localStorage的值总是一个字符串。那么,我该怎么做呢?

var val = localStorage.getItem("key3")
if (val is a previously JSON.stringify'd object) // <-- ??
    return JSON.parse(val)

Do I need to do a regex check on val, and if so, does anyone have a pattern handy which tells me if a string is really a JSON.stringify'd object?

我是否需要对val进行正则表达式检查,如果是这样,是否有人有方便的模式告诉我字符串是否真的是一个JSON.stringify对象?

Thanks!

3 个解决方案

#1


2

Another option is to store an object {isJsonObj:true, jsonObj: jsonObj}, and check the type is Object, and isJsonObj is true. If either of those are false, then it isn't a json obj (this means you don't have to parse). I realise this means you won't always have a string in there, but it makes it easy to test, and won't carry a large amount of overhead.

另一种选择是存储一个对象{isJsonObj:true,jsonObj:jsonObj},并检查类型是否为Object,并且isJsonObj为true。如果其中任何一个都是假的,那么它不是json obj(这意味着你不必解析)。我意识到这意味着你不会总是有一个字符串,但它使测试变得容易,并且不会带来大量的开销。

更多相关文章

  1. 令人惊奇的JavaScript面向对象(一)
  2. JavaScript面向对象程序设计三——原型模式(上)
  3. Safari / Chrome中的全局控制台对象被重置
  4. 错误对象,本机和自定义,如何区分?
  5. JavaScript相当于Ruby的字符串#扫描
  6. 11、javascript中字符串常用操作总结、JS字符串操作大全
  7. 从占用转义字符的字符数组创建字符串
  8. 高效地获取XMLhttp对象
  9. javascript如何取字符串中的数字

随机推荐

  1. [转]Composite Keys With WebApi OData
  2. 总结EF通用数据层封装类实例详解
  3. [转]Support Composite Key in ASP.NET W
  4. 学习ASP.NET Core 2遇到的问题分享
  5. 使用ConcurrentDictionary多线程同步字典
  6. 浅谈WPF之Binding表达式
  7. 一个很强大的控件--PropertyGrid
  8. 克隆对象的方法实例教程
  9. 分享html元素调用服务器实例
  10. C#基础之操作优化实例教程