我是 JavaScript 新手。有人请告诉我如何将地图存储在本地存储中。以下是我尝试过的。存储后我似乎无法迭代映射键。UDATE2:它可能是 serializeObject 函数。为什么我要使用这个功能?否则,当我在 AJAX 中发布时,我得到:未捕获的 TypeError:将循环结构转换为 JSON
更新:看起来问题是在它进入本地存储之前。
var reportId = getGUID();
var theReports = localStorage.getItem('reports');
if (theReports == null) {
theReports = {};
}
theReports[reportId] = JSON.stringify($('#reportInfo').serializeObject());
// HERE ALSO I AM SEEING HUNDREDS OF FIELDS. I EXPECTED JUST reportID. I AM NOT SEEING THE KEY reportId. THIS IS BEFORE IT GOES INTO LOCAL STORAGE.
for (var prop in theReports)
{
console.log(prop);
}
localStorage.setItem('reports', JSON.stringify(theReports));
var tReports = localStorage.getItem('reports');
// This prints out 1,2,3,...500 for every field in #reportInfo form
// What I was expecting is reportId1, reportId2 etc. and definitely not the id of each field of the report itself!
for (var property in tReports) {
if (tReports.hasOwnProperty(property)) {
console.log(property);
}
}
这是 serializeObject 函数。也许这就是问题所在。
$(function() {
$.fn.serializeObject = function(){
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value){
base[key] = value;
return base;
};
this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function(){
// skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while((k = keys.pop()) !== undefined){
// adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
// push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}
// fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}
// named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}
json = $.extend(true, json, merge);
});
return json;
};