如何在localStorage(Javascript)中存储带有数组的JSON?

时间:2015-10-05 12:19:20

标签: javascript html arrays json html5

我正在为我的项目开发HTML5游戏,我的问题在于评分系统 我想展示十大最佳得分手(已经排序)。我目前正在使用JSON中的Array。

现在我想在localStorage中保存JSON数组

var storage = '{"Players":[' +
        '{"score":"0","Name":"Player 2"},' +
        '{"score":"0","Name":"Player 4"},' +
        '{"score":"0","Name":"Player 1"}]}';

var obj = JSON.parse(storage);

obj['Players'].push({"score": 13,"Name": "Player1"});
obj['Players'].push({"score": 523,"Name": "Player2"});
obj['Players'].push({"score": 3,"Name": "Player3"});
obj['Players'].push({"score": 1235,"Name": "Player4"});

storage = JSON.stringify(obj);

var sortColumnScore = "score";

function SortByScore(x,y) {
    return ((x[sortColumnScore]  == y[sortColumnScore]) ? 0 : ((x[sortColumnScore] < y[sortColumnScore]) ? 1 : -1 ));
}

obj.Players.sort(SortByScore);

for (var i = 0; i < 5; i++) {
    document.getElementById("s"+ (i+1)).innerHTML =
    obj.Players[i].score;
    document.getElementById("p"+ (i+1)).innerHTML =
    obj.Players[i].Name;
};

3 个答案:

答案 0 :(得分:1)

基本上你应该像使用上面的storage一样使用localstorage。您可以像对待@Magus一样以对象的方式使用localstorage,也可以以关联数组的方式使用localstorage,调用其原语getItemsetItem

简单用法:

var storage = '{"Players":[' +
    '{"score":"0","Name":"Player 2"},' +
    '{"score":"0","Name":"Player 4"},' +
    '{"score":"0","Name":"Player 1"}]}';

var obj = JSON.parse(storage);

obj['Players'].push({"score": 13,"Name": "Player1"});
obj['Players'].push({"score": 523,"Name": "Player2"});
obj['Players'].push({"score": 3,"Name": "Player3"});
obj['Players'].push({"score": 1235,"Name": "Player4"});

localStorage.setItem('Players', JSON.stringify(obj));

然后从localStorage调用获取数据:

var myobj = JSON.parse(localStorage.getItem('Players'));

高级用法:

为正确使用(加上当前用户会话)和localstorage / sessionstorage的初始化(根据您的目标),请参阅@ War10ck在此问题Push JSON Objects to array in localStorage后的评论。

答案 1 :(得分:0)

localStorage不能包含对象或数组。但你可以用字符串转换它。

// Store the object
localStorage.myObject = JSON.stringify(myObject);

// Read the object
var myObject = JSON.parse(localStorage.myObject);

答案 2 :(得分:0)

localStorage获取项目:

var str = localStorage.getItem('my-item');

localStorage中保存项目:

localStorage.setItem('my-item', str);

注意:您只能将字符串保存到localStorage,因此,您需要通过JSON.stringify将数据转换为字符串,然后在从localStorage检索字符串时使用JSON.parse