JavaScript

[JavaScript] localStorage 에 Array 형태로 저장, JSON.stringify() /JSON.parse()

mswait 2022. 3. 2. 20:30

JSON.stringify(Array);

 

localStorage에는 배열이 배열의 형태로 저장되지를 않는다.

const toDos = [];

배열을 담으려고 하면?

localStorage.setItem("todos", toDos);

출력에서는 toDos가 배열임이 확인된다 하지만 배열을 로컬스토리지에 저장하려고 하면
저장도 string 으로만 되고 

 

가져온 결과물도 string 의 형태를 띈다 

이를 JSON.stringify() 로 애시당초 배열 전체를 string으로 변환해주고 localStorage에 넣어주면?

localStorage.setItem("todos", JSON.stringify(toDos));

잘출력이 된다.

 

이를 이제 다시 Array로 변환하는 방법은

JSON.parse()

string을 실제로 무언가를 할 수 있는 Array로 변환하는데 성공했다!

https://nomadcoders.co/javascript-for-beginners/lectures/2918

 

All Courses – 노마드 코더 Nomad Coders

초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!

nomadcoders.co