【发布时间】:2015-07-02 04:13:38
【问题描述】:
我在stackoverflow上看到了当前的解决方案,例如:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
但我正在尝试做类似的事情: localStorage[a][b] = 5 带有函数调用 localStorage.setItem('a', 'b', 5)。
我目前的代码由于引用问题而无法正常工作:
Storage.prototype.setVal = function(key, val) {
var val = Array.prototype.pop.call(arguments);
var cur_depth = this;
for (var i in arguments) {
var cur_key = arguments[i];
cur_depth = JSON.parse(cur_depth[cur_key]);
}
cur_depth = JSON.stringify(val);
}
我最后一次,甚至更老套的尝试:
Storage.prototype.setVal = function(key, val) {
var val = JSON.stringify(Array.prototype.pop.call(arguments));
var keys = ''; // hacky eval solution
for (var i in arguments) {
var cur_key = arguments[i];
keys += '["' + cur_key + '"]';
}
eval('this' + keys + '=' + val);
}
【问题讨论】:
标签: javascript html dictionary nested local-storage