具有负数和大数组索引的变量值不会保存在本地存储中
Values of variables with negative and big array indexes does not save in local storage
我有不常见数组索引的变量。这里是:
http://i.imgur.com/01nH8x5.png
所以,我将它保存到本地存储中:
function Save(){
var save = {
//<...>
MapCellData: MapCellData,
MapCellDataE: MapCellDataE
//<...>
};
localStorage.setItem("save",JSON.stringify(save));
}
window.setInterval(function(){
Save()
}, 10000); // Autosave every 10 sec
然后我转到 Firebug 控制台并通过输入以下命令检查保存了哪些元素:
JSON.parse(localStorage.getItem("save"));
这是我得到的:http://i.imgur.com/vva3mBk.png
如您所见,具有负索引和大索引的变量的所有值都未定义,而索引从 0 到 4 已正确保存。
注意:MapCellData 是决定将哪个图像应用于 table 单元格的变量,而 MapCellDataE 是决定单元格背景颜色的变量。这两个变量都有相同的索引,因此它们都有相同的问题。没有如此奇怪索引的变量可以正确保存。
这是它的外观。
在我重新加载页面之前:http://i.imgur.com/B3FSu5e.png
重新加载页面后:http://i.imgur.com/rhkZAa1.png
是的,JSON.stringify
does only serialise array indices1 on Array
objects, and discards all other properties. The solution is trivial - don't use arrays when you shouldn't be using them:
var MapCellData = {}; // instead of []
MapCellData[weirdProperty] = …;
考虑到您的 "array" 有多稀疏,这在 JSON 中也会更加 space 高效。
1: §6.1.7, §9.4.2: 数组索引是一个字符串值 属性 键,它是一个规范的数字字符串,其数值 i 在 +0 ≤ 范围内我 < 232−1.
我有不常见数组索引的变量。这里是: http://i.imgur.com/01nH8x5.png
所以,我将它保存到本地存储中:
function Save(){
var save = {
//<...>
MapCellData: MapCellData,
MapCellDataE: MapCellDataE
//<...>
};
localStorage.setItem("save",JSON.stringify(save));
}
window.setInterval(function(){
Save()
}, 10000); // Autosave every 10 sec
然后我转到 Firebug 控制台并通过输入以下命令检查保存了哪些元素:
JSON.parse(localStorage.getItem("save"));
这是我得到的:http://i.imgur.com/vva3mBk.png
如您所见,具有负索引和大索引的变量的所有值都未定义,而索引从 0 到 4 已正确保存。
注意:MapCellData 是决定将哪个图像应用于 table 单元格的变量,而 MapCellDataE 是决定单元格背景颜色的变量。这两个变量都有相同的索引,因此它们都有相同的问题。没有如此奇怪索引的变量可以正确保存。
这是它的外观。
在我重新加载页面之前:http://i.imgur.com/B3FSu5e.png
重新加载页面后:http://i.imgur.com/rhkZAa1.png
是的,JSON.stringify
does only serialise array indices1 on Array
objects, and discards all other properties. The solution is trivial - don't use arrays when you shouldn't be using them:
var MapCellData = {}; // instead of []
MapCellData[weirdProperty] = …;
考虑到您的 "array" 有多稀疏,这在 JSON 中也会更加 space 高效。
1: §6.1.7, §9.4.2: 数组索引是一个字符串值 属性 键,它是一个规范的数字字符串,其数值 i 在 +0 ≤ 范围内我 < 232−1.