如何将数据添加到本地存储?

时间:2014-05-16 04:53:38

标签: javascript jquery

我正在制作一个游戏应用程序。
最初我制作了两个loaclstorage,一个是userCard,另一个是CompCard,我在本地存储中添加了3个板球玩家卡片细节。

我的2个本地存储及其deatils:

var user_Card =  [["Nixon", "McLean", "West Indies", 
                   45, 314, 0, 1, "12.07", "37.58", 
                   46, 3, 21, 8, 
                   "img/cards/7RBKWQPJAG_NixonMcLean.jpg", 1], 
                  ["Brian", "McMillan", "South Africa", 78,  
                    841, 1, 0, "23.36", "36.98", 70, 4, 32, 43,
                    "img/cards/Y9U5UKA60O_BrianMcMillan.jpg", 2], 
                  ["Craig", "McMillan", "New Zealand", 197, 4707, 3,
                    28, "28.18", "35.04", 49, 3, 20, 44, 
                   "img/cards/WE0NUNG80C_CraigMcMillan.jpg", 3]
                 ];             

var comp_Card =  [["Geoff", "Miller", "England", 25, 136, 0, 0, 
                  "8.5", "32.52", 25, 3, 27, 4, 
                  "img/cards/7ZPIQXC19H_GeoffMiller.jpg", 4], 
                  ["Kyle", "Mills", "New Zealand", 165, 1016, 
                    0, 2, "15.87", "26.74", 235, 5, 25, 40, 
                   "img/cards/P43DTA4ZCX_KyleMills.jpg", 5], 
                  ["Minhazul", "Adedin", "Bangladesh", 27, 453, 0, 2, 
                   "18.87", "39.3", 13, 2, 39, 2, 
                    "img/cards/CC8ENY3E09_MinhazulAdedin.jpg", 6]
                  ];

userCard =JSON.parse(localStorage['user_Card']);
compCard =JSON.parse(localStorage['comp_Card']);

当我检索所有卡片的详细信息即将到来时,usercard[0]compcard [0]是第一张卡片,usercard[1]是第二张卡片,usercard[2]是第三张卡片,

我的问题是,当我玩游戏时,如果用户卡获胜,我想将失去的复合卡添加到用户卡本地storgae。如果compcard wins将丢失的用户卡添加到compcard本地存储中。

假设userCard[0]是第一张牌            compcard[0]是第一张卡

当我玩游戏时,如果userCard[0]获胜,我想在本地存储用户卡中添加丢失compcard[0],如果compCard[0]获胜,我想添加丢失usercard[0]到{{1}} localstorage compCard

请为我提供解决方案。

1 个答案:

答案 0 :(得分:1)

如何阅读Offline Technologies

  

Web Storage只提供键值映射,例如   localStorage [“name”] = username;。不幸的是,现在   实现仅支持字符串到字符串映射,因此您需要   序列化和反序列化其他数据结构。你可以这样做   JSON.stringify()和JSON.parse()。

所以你应该尝试这样的事情:

var userCard =JSON.parse(localStorage.['user_Card']);
userCard.push(compCard[0]);

localStorage.['user_Card'] = JSON.stringify(userCard));