如何在javascript中使用localstorage for arrays [英] How to use localstorage for arrays in javascript
问题描述
您好!我正在尝试使用本地存储来保存我的一个数组,pokemonchosen.here是代码:
var pokemonchosen = [];
如果刷新或浏览器关闭,阵列pokemonchosen会保持原样,我该怎么做?但是我有一个比其他人更奇怪的问题,pokemonchosen没有价值,直到有人购买口袋妖怪,在这种情况下:
pokemonchosen。 push(Charmander);
我如何在购买口袋妖怪的地方设置本地存储?这是口袋妖怪的许多功能之一:
function buymagikarp(){
if(coins> = 100){
swal(成功,你买了1个magikarp!,成功);
币 - = 100;
pokemonchosen.push(Magikarp);
document.getElementById(p1)。innerHTML =硬币:+硬币;
localStorage.setItem('coins',coins);
} else {
swal(错误,余额不足,错误);
}
}
谢谢:-)
我尝试过:
if(pokemonchosen!= undefined){
var JSONReadyUsers = JSON.stringify(pokemonchosen);
localStorage.setItem('pokemonchosen',JSONReadyUsers)
}
你的代码我有什么试过会工作,所以你已经有了!以下是如何再次加载数组:
pokemonchosen = JSON .parse(localStorage.getItem( ' pokemonchosen'));
< a href =https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse> JSON.parse() - JavaScript | MDN [ ^ ]
Hello! I am trying to use local storage to save one of my arrays, pokemonchosen.here is the code:
var pokemonchosen = [];
How would I make it to where if refresh or browser close, the array pokemonchosen stays like it is? But I have a weirder problem than others, pokemonchosen doesn't have a value until someone buys a pokemon, in which case:
pokemonchosen.push("Charmander");
How would I make it where sets local storage on buy pokemon? This is one of many functions for pokemon:
function buymagikarp() { if(coins >= 100 ) { swal("Success", "You bought 1 magikarp!", "success"); coins -= 100; pokemonchosen.push("Magikarp"); document.getElementById("p1").innerHTML = "Coins: " + coins; localStorage.setItem('coins', coins); } else { swal("Error", "Not enough balance", "error"); } }
Thank you :-)
What I have tried:
if(pokemonchosen != undefined) { var JSONReadyUsers = JSON.stringify(pokemonchosen); localStorage.setItem('pokemonchosen', JSONReadyUsers) }
Your code in "What I have tried" will work, so you have that already! Here is how you can load the array again:
pokemonchosen = JSON.parse(localStorage.getItem('pokemonchosen'));
这篇关于如何在javascript中使用localstorage for arrays的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!