Local Storage value에 배열 생성 등

woong3e·2023년 5월 13일
0
post-thumbnail

Local Storage 에 배열 setItem, getItem 을 해보자

const name = "개똥이";
console.log(name);
localStorage.setItem("name", name);
localStorage.getItem("name");
console.log("이건 가져온거" + localStorage.getItem("name"));

/* localStorage에 배열 생성하기 */
const commentKey = "commentKey";
const array = ["1", "2", "3", "4"];
const arrayStr = JSON.stringify(array);
localStorage.setItem(commentKey, arrayStr);
console.log(array);
console.log("문자형태로 바꾼 배열", arrayStr);

/* localStorage에 배열 가져오기 */
JSON.parse(localStorage.getItem(commentKey));
console.log(
  "parse하면 다시 배열형태로",
  JSON.parse(localStorage.getItem(commentKey))
);

정리

localStorage 파라미터값은 key:string, value:string 이기 때문에 배열을 넣을 때에는 배열형태를 string형태로 바꾸어서 넣어줘야한다.
그 과정에서 쓰이는게 JSON.stringify 와 JSON.parse이다.
배열을 넣고 빼고 수정하려면 배열형태에서 push pop shift등을 한뒤에 다시 문자열로 바꾸어 넣어주면 된다.

0개의 댓글