使用localStorage来计算

时间:2012-03-02 21:04:02

标签: javascript json local-storage

var nicWinsVsMac;

 if (tempresult === win) {
            wincount = JSON.parse(localStorage.getItem (playerName + 'wincount'));
            wincount += 1;
            localStorage.setItem(playerName + 'wincount', wincount);

        winsvsopponent = 'WinsVs' + opponent;
        winsvsopponent = JSON.parse(localStorage.getItem(playerName + 'WinsVs' + opponent));
        winsvsopponent  += 1;
        console.log(winsvsopponent);
        localStorage.setItem(playerName + 'WinsVs' + opponent, 'winsVs' + opponent); 
        console.log(localStorage.getItem(nicWinsVsMac));    
    }

playerNameopponent是传入的参数。在这种情况下,playerName = 'nic'opponent = "Mac"

我的浏览器在我解析localStorage的行上给了我“意外的令牌w”。我无法弄清楚发生了什么。任何帮助都会很棒。谢谢!

1 个答案:

答案 0 :(得分:0)

而不是为播放器的每个属性使用单独的localStorage变量。为什么不将所有玩家属性存储在单个对象中,然后将其保存到localStorage。

例如,您可以执行以下操作:

var player = new Object();
player.name = 'Mac';
player.winCount = 3;
player.winAgainst = new Array();

localStorage.setItem(player.name, JSON.stringify(player));

var player1 = JSON.parse(localStorage.getItem(player.name));
console.log(player1.name + " has " + player1.winCount + " wins.");

这允许您将所有玩家的属性保存到单个localStorage变量,使其更容易读取和写入。

关于您收到的错误,我相信您的代码的问题是您在调用setItem时没有使用JSON.stringify。