1

这是对此的后续问题

我开始使用 localStorage 功能,但不确定它是否按预期工作。

我想覆盖我的 JSON 文件中的布尔值。

玩家在一个阶段点击出口,然后触发下一个阶段的加载,但我也希望它保存阶段完成的事实。

这是我的 JSON 数组,默​​认情况下所有地牢都不完整:

var dungeon_prog = {
"dungeon0_prog" : {
    "complete" : true
},
"dungeon1_prog" : {
    "complete" : false
},
"dungeon2_prog" : {
    "complete" : false
}
};

然后我将其设置为本地存储:

localStorage.setItem('dungeon_prog', JSON.stringify(dungeon_prog));
var dungeon_prog_obj = JSON.parse(localStorage.dungeon_prog);

false我希望它在玩家到达true地牢 1 的出口时覆盖 dungeon1_prog “完成” 。

我该怎么做?并且默认的“假”语句实际上是否保存在 localStorage 中?谢谢。

4

1 回答 1

2

The dungeon_prog_obj now holds your JSON object. To answer your last question, yes - localStorage saves the entire JSON string, thus it also saves the boolean values.

To overwrite it you just have to set the boolean value and them save again to the same localStorage item:

dungeon_prog_obj.dungeon1_prog.complete = true;
localStorage.setItem('dungeon_prog', JSON.stringify(dungeon_prog_obj));

Edit:

Update in order to answer questions in the comment, per request.

I am not 100% sure that this is the issue, but you are saying that on page refresh the true value does not persist. The only plausible explanation is that on every page load you are overwriting the JSON with the initial one using localStorage.setItem('dungeon_prog', JSON.stringify(dungeon_prog));, where dungeon_prog is the initial JSON specified in your question.

Instead of doing this, you should check on load if you have the item in localStorage. You can do this in the following way:

// Check for object in localStorage
var dungeon_prog = JSON.parse(localStorage.dungeon_prog);

// If it does not exist, initialize it and save it
if (dungeon_prog != null) {
    dungeonProg = {
        "dungeon0_prog" : {
            "complete" : true
    },
    "dungeon1_prog" : {
        "complete" : false
    },
    "dungeon2_prog" : {
        "complete" : false
   }
   };

   localStorage.setItem('dungeon_prog', JSON.stringify(dungeon_prog));
}
于 2013-12-16T09:57:45.127 回答