본문 바로가기

WEB

[ LocalStorage ] localStorage에서 배열(Array)다루기.

 

 

최근 작업 할 부분이 client측에서 `localStorage`를 통해 배열을 저장, 수정, 삭제하는 기능을 구현해야 해서 정리해 보았다.  (localStorage는 웹 브라우저의 클라이언트 측에 데이터를 저장하는 데 사용되는 웹 스토리지) 

 

 

 

 


1. 배열을 `localStorage`에 저장하기:

// 예시 배열
const myArray = [1, 2, 3, 4, 5];

// 배열을 JSON 문자열로 변환하여 localStorage에 저장
localStorage.setItem('myArray', JSON.stringify(myArray));

* localStorage는 value에 문자열만 가능하기 때문에, JSON.stringufy()를 이용하여 배열을 문자로 바꾸어 저장해야한다. 

 

 

 

 



2. `localStorage`에서 배열 불러오기:

// 저장된 배열을 JSON 문자열 형태로 가져온 후 파싱하여 JavaScript 배열로 변환
const storedArray = JSON.parse(localStorage.getItem('myArray'));

// storedArray를 사용하여 작업 수행
console.log(storedArray); // [1, 2, 3, 4, 5]

 

 

 

 

 



3. 배열에 데이터 추가하기:

const storedArray = JSON.parse(localStorage.getItem('myArray'));

// 배열에 데이터 추가
storedArray.push(6);
storedArray.push(7);

// 변경된 배열을 다시 localStorage에 저장
localStorage.setItem('myArray', JSON.stringify(storedArray));

 

 

 

 

 



4. 배열에서 데이터 제거하기:

const storedArray = JSON.parse(localStorage.getItem('myArray'));

// 특정 요소 제거
const indexToRemove = 2; // 인덱스 2에 해당하는 요소 제거
storedArray.splice(indexToRemove, 1);

// 변경된 배열을 다시 localStorage에 저장
localStorage.setItem('myArray', JSON.stringify(storedArray));

 

 

 

 

 



5. 배열 초기화 또는 삭제하기:

// 배열 초기화 (빈 배열로 설정)
const emptyArray = [];
localStorage.setItem('myArray', JSON.stringify(emptyArray));

// 또는 배열 전체 삭제
localStorage.removeItem('myArray');

 

 

 

 

 


 

🌸 출처 🌸

 

 

LocalStorage - MDN

JSON.stringify() - MDN

JSON.parse() - MDN