minlog
Published 2023. 8. 14. 15:21
[ Javascript ] 배열 FrontEnd/Javascript

JAVASCRIPT 배열

 

1. 기존 배열을 가지고 새로운 배열 생성.

  • map() : 결과 값을 배열로 생성
  • filter() : 일치하는 값을 배열로 생성
const numbers = [1,2,3,4];

const a = numbers.map(num => num < 3);
console.log(a)
// 결과 값  [true,true,false,false]

const b = numbers.filter(num => num < 3);
console.log(b)
// 결과 값  [1,2]

 

 

2. 조건 특정 값 찾기 

  • .find() : 조건의 특정한 값을 찾으면 해당 값을 전달하고 루프가  멈춘다.
  • .findIndex() :조건에 맞는 값의 배열 인덱스를 전달하고 루프가 멈춘다.
const fruits = ['Apple','Banana','Cherry'];

const a = fruits.find(fruit =>{
	return /^B/.text(fruit);
});

// 결과값 Banana

const b = fruits.findIndex(fruit =>{
	return /^B/.text(fruit);
});

// 결과값 1 --> 0 부터 인덱스 번호를 반환

 

  • includes() : 특정 배열에 값이 포함이 되어있는지 확인
const numbers = [1,2,3,4];
const fruits = ['Apple','Banana','Cherry'];

const a = numbers.includes(4);
// 결과값 true

const b = fruits.includes('HAHA');
// 결과값 false

 

 

3. 기존 배열의 수정

  • .push() : 배열 데이터의 가장 마지막에 해당 아이템이 삽입된다.
  • .unshift() : 배열 데이터의 가장 앞에 해당 아이템이 삽입된다.
  • .reverse() : 기존 배열의 순서를 거꾸로 뒤집는다.
const numbers = [1,2,3,4];

numbers.push(5);
// 결과값 [1,2,3,4,5]

numbers.unshift(0);
// 결과값 [0,1,2,3,4,5]

numbers.reverse();
// 결과값 [5,4,3,2,1,0]

 

 

splice를 사용한 아이템 제거와 추가

  • .splice(인덱스 값, 제거할 아이템 수) : 배열데이터에서 일정 아이템을 제거할때 사용
  • .splice(인덱스 값, 제거할 아이템 수, 생성할 아이템 ) : 배열데이터에서 일정 아이템을 해당 위치에 추가
const numbers = [1,2,3,4];

numbers.splice(2,1);
// [1,2,4]

numbers.splice(2,2);
// [1,2]

numbers.splice(2,0,999);
// [1,2,999,3,4]


numbers.splice(2,1,99);
// [1,2,99,4]

 

 

 

profile

minlog

@jimin-log

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!