简体   繁体   中英

Adding an array of objects to local storage in javascript?

tried saving an array of objects into localStorage and then getting it back.

for some reason in console the new arr is empty (history = []) and in localStorage, savedgameHistory = [{},{}]

*SORRY, I didn't explain myself right. I need to save the array order. in order to use it in an UNDO button.


const img1 = document.getElementById("img1"); // img tag
const img2 = document.getElementById("img2"); // img tag

let arrOfObj = [img1, img2]

function saveGame(){
localStorage.setItem("savedgameHistory", JSON.stringify(arrOfObj));
window.location.href = "./TicTacToe.html";
}

function loadGame(){
 const history = JSON.parse(localStorage.getItem("savedgameHistory"));
}

You don't save the image tag in the local storage, instead, you save a string, the string you want to save is the src attribute of the image, so you save it as follows:

 const img1 = document.getElementById("img1"); // img tag const img2 = document.getElementById("img2"); // img tag let arrOfObj = [img1.src, img2.src] function saveGame() { localStorage.setItem("savedgamehistory", JSON.stringify(arrOfObj)); window.location.href = "./TicTacToe.html"; } function loadGame() { const history = JSON.parse(localStorage.getItem("savedgameHistory")); }

then, after you load it, you treat it as an src string, so you place it directly on your image tag in your html file, ex:

<img id="img1" />
<img id="img2" />
function loadGame() {
  const history = JSON.parse(localStorage.getItem("savedgameHistory"));
  img1.src = history[0]  
  img2.src = history[1]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM