-
javascript 배열 함수 (concat, filter, map, slice, spread)react+vue 2022. 9. 21. 14:11
리액트에서 배열을 다루는 것
리액트에서는 UI의 각 요소를 컴포넌트화 하여 화면을 만든다.
컴포넌트화 한 화면의 요소를 배열에 저장하여 배열을 가공하는 것이 중요하다.
아래에서 배열을 가공할 수 있는 함수와 전개 연산자의 활용법을 작성하겠다.
배열
const a = [1,2,3];
concat
- 새로운 배열을 만들어서 추가하기
const a = [1,2,3]; const b = a.concat(4); console.log(a);//[1,2,3] console.log(b);//[1,2,3,4]
const c = [...a,4];//concat과 같다
filter
- 걸러내기
- bool을 return 받고, true만 걸러낸다.
- 보통 배열의 요소를 삭제할 때 쓴다.
const a = [1,2,3]; const b = a.filter((n)=>{return n!=1;}); console.log(b); //[2,3]
map
- 배열요소를 반복하여 반환하기
const a = [1,2,3]; for(let i = 0; i<a.length; i++){ console.log(a[i]); } //jsx에서는 불가능하다. a.forEach((i)=>{ console.log(i); }); //return 불가능 const b = a.map((n)=>n);//[...a]와 같다 console.log(b);//[1,2,3] 깊은복사 const c = a.map((n)=>{n--; return n;}); console.log(c);//[0,1,2]
slice
- 배열을 잘라낸다.
const a = [1,2,3]; const b = a.slice(0,2); console.log(b);//[1,2]
- 삽입하기
const c = [...a.slice(0,2),4,...a.slice(2,3)]; console.log(c);//[1,2,4,3] 4가 중간에 삽입된다.
spread 연산자
- 깊은 복사
const a = [1,2,3]; const b = [...a]; b.push(4); console.log(a);//[1,2,3]출력
- 얕은 복사
const a = [1,2,3]; const b = a; b.push(4); console.log(a);//[1,2,3,4]출력
map spread 응용
const users = [ {id:1,name:"홍유진",phone:"010-1111-2222"}, {id:2,name:"홍유",phone:"010-1111-2222"}, {id:3,name:"홍",phone:"010-1111-2222"} ]; const updateUserDto = {id:2,name:"홍길동"}; const newUsers = updateUserDto.map((u)=>{ u.id === updateUserDto.id? {...u,...updateUserDto}:u; });
'react+vue' 카테고리의 다른 글
[javascript] import/export 방법 (0) 2022.09.21 [react] useEffect (0) 2022.09.21 [react] useState (1) 2022.09.21 react 개념 (0) 2022.09.20 react 설치 (0) 2022.09.20