<!-- Always use a CDN for external libraries! i.e. https://cdnjs.com/ --><!-- The usage of CDN will help reduce net traffic thanks to browser cache --><linkhref="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"><scriptsrc="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
history.length// the total number of history entrieshistory.back()// go back oncehistory.back()// go back oncehistory.forward()// go forward oncehistory.go(5)// go forward 5 entrieshistory.go(-2)// go back 2 entrieshistory.pushState(null,null,'contact')// add a new entry as if you have gone one page further, with no page refreshhistory.replaceState()// replaces the current entry
localStorage.setItem('myCat','Tom');localStorage.getItem('myCat')==='Tom';localStorage.removeItem('myCat');localStorage.clear();// localStorage only supports string data// save arrays or objects as JSON string to localStorage// parse JSON string back to array or object when neededconstcats=['Tom','Infinnity','Puss','Kitty'];localStorage.setItem('cats',JSON.stringify(cats));localStorage.getItem('cats');// -> '["Tom", "Infinnity", "Puss", "Kitty"]'conststoredCats=JSON.parse(localStorage.getItem('cats'));
Ukládání do localStorage
do localStorage ukládáme data v podobě, s jakou budeme pracovat v kódu po extrakci z localStorage
neukládáme všechna data ale pouze klíčové informace jako identifikátor, popř. název, a další vlastní data, související data stahujeme znovu z API podle uložených informací
Příklad: nechť máme nějaké knižní záznamy a chceme je všechny uložit do localStorage
constbooksData=[{"id": "0","title": "Harry Potter and the Philosopher's stone"},{"id": "1","title": "Harry Potter and the Chamber of Secrets"}...];localStorage.setItem('bookIds',JSON.stringify(booksData.map((book)=>book.id)));localStorage.getItem('bookIds');// ["1", "2"]
pokud budeme chtít mazat jednotlivé záznamy, tak je ukládáme nejlépe do objektu (ale ztratíme tím pořadí záznamů)
constbooks={};items.forEach((item)=>{books[item.id]=item.title;});console.log(books);// { "1": "Harry Potter and the Philosopher's stone", "2": "Harry Potter and the Chamber of Secrets" }localStorage.setItem('books',JSON.stringify(books));deletebooks['1'];console.log(books);// { "2": "Harry Potter and the Chamber of Secrets" }localStorage.setItem('books',JSON.stringify(books));deletebooks['2'];console.log(books);// {}localStorage.setItem('books',JSON.stringify(books));
pokud budeme chtít mazat jednotlivé záznamy a chceme zachovat pořadí záznamů, můžeme použít metodu .filter nad polem
constbooksData=[{"id": "0","title": "Harry Potter and the Philosopher's stone"},{"id": "1","title": "Harry Potter and the Chamber of Secrets"}];console.log(booksData);// [ { "id": "0" }, { "id": "1" } ];constbookIdToRemove='1';constremainingBooksData=booksData.filter((book)=>book.id!==bookIdToRemove);console.log(remainingBooksData);// [ { "id": "0" } ];