localStorage.setItem("saveTab",[1,2,3])
console.log(localStorage.getItem("saveTab")
> 1,2,3
Il faut utiliser JSON
localStorage.setItem("saveTAB",JSON.stringify([1,2,3]))
console.log(localStorage.getItem("saveTAB"))
> [1,2,3] // ce n'est pas un tableau mais un string
typeof localStorage.getItem("saveTAB")
> 'string'
Il faut utiliser JSON.parse
console.log(JSON.parse(localStorage.getItem("saveTAB")))
VM1856:1 (3) [1, 2, 3]
0: 1
1: 2
2: 3
length: 3[[Prototype]]: Array(0)
typeof JSON.parse(localStorage.getItem("saveTAB"))
'object'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Document</title> | |
<script src="random-words.js" defer></script> | |
</head> | |
<body> | |
<h1>random word</h1> | |
<ul id="list"></ul> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//UI | |
const list = document.getElementById('list'); | |
//random words | |
const load = async () => { | |
const sortable = JSON.parse(localStorage.getItem("words")) | |
if (!sortable) { | |
const data = await fetch("https://random-word-api.herokuapp.com/word?number=20"); | |
const words = await data.json(); | |
const alphabetical = words.reduce((a, x) => { | |
if (!a[x[0]]) a[x[0]] = []; | |
a[x[0]].push(x); | |
return a; | |
}, {}); | |
// console.log(alphabetical) | |
const sortable = Object.fromEntries( | |
Object.entries(alphabetical).sort(([a,], [b,]) => { | |
if (a > b) { | |
return -1 | |
} else { | |
return 1 | |
} | |
}) | |
); | |
localStorage.setItem("words", JSON.stringify(sortable)); | |
return sortable; | |
} else { | |
return sortable; | |
} | |
} | |
// UI | |
(async () => { | |
const words = await load(); | |
Object.entries(words).forEach(([letter, words]) => { | |
// console.log(letter, words) | |
const tempLi = document.createElement('li') | |
, tempUl = document.createElement('ul'); | |
words.forEach((word) => tempUl.insertAdjacentHTML('afterbegin', `<li> ${word} </li>`)) | |
tempLi.insertAdjacentElement('beforeend', tempUl) | |
.insertAdjacentText('beforebegin', `${letter}`) | |
document | |
.querySelector("#list") | |
.insertAdjacentElement('afterbegin', tempLi) | |
}) | |
})() |