부트캠프

배열과 배열 메서드

mimi-latte 2022. 5. 10. 21:24

배열

  • 여러 개의 변수를 한 번에 선언해 다룰 수 있는 자료형
  • 대괄호를 사용해 생성하며 내부의 값은 쉼표로 구분
  • 요소 : 배열 내부에 들어 있는 값
  • 배열은 순서에 대한 정보(index)를 가지고 있는 (참조형)데이터

 

배열 메서드

split()

  • String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다.
  • 매개변수1(optional) : separator. 원본 문자열을 끊어야 할 부분을 나타내는 문자열
  • 매개변수2(optional) : limit. 끊어진 문자열의 최대 개수를 나타내는 정수
  • 반환값 : 주어진 문자열을 separator마다 끊은 부분 문자열을 담은 Array
  • 사용 예시)
const str = '맛있는 치즈 뿌린 치킨팝';

const words = str.split(' ');
console.log(words[3]);
// 결과 : "치킨팝"

const chars = str.split('');
console.log(chars[8]);
// 결과 : "린"

const strCopy = str.split();
console.log(strCopy);
// 결과: Array ["맛있는 치즈 뿌린 치킨팝"]

 

join()

  • 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.
  • 매개변수1(optional) : separator. 배열의 각 요소를 구분할 문자열
  • 반환값 : 배열의 모든 요소들을 연결한 하나의 문자열을 반환. 만약 arr.length 가 0이라면, 빈 문자열을 반환합니다.
  • 사용 예시)
const elements = ['푸', '라', '닭'];

console.log(elements.join());
// 결과: "푸,라,닭"

console.log(elements.join(''));
// 결과: "푸라닭"

console.log(elements.join('-'));
// 결과: "푸-라-닭"

 

 

slice()

  • 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환
  • 원본 배열은 바뀌지 않는다.
  • 매개변수1(optional) : begin. 0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미. 음수는 배열 끝에서부터의 길이를 의미.
  • 매개변수2(optional) : end. 추출을 종료 할 0 기준 인덱스. slice  end 인덱스를 제외하고 추출.
  • 반환값 : 추출한 요소를 포함한 새로운 배열
  • 사용 예시)
const number = ['one', 'two', 'three', 'four', 'five'];

console.log(number.slice(2));
// 결과: Array ['three', 'four', 'five']

console.log(number.slice(2, 4));
// 결과: Array ['three', 'four']

console.log(number.slice(1, 5));
// 결과: Array ['two', 'three', 'four', 'five']

console.log(number.slice(-2));
// 결과: Array ['four', 'five']

console.log(number.slice(2, -1));
// 결과: Array ['three', 'four']

console.log(number.slice());
// 결과: Array ['one', 'two', 'three', 'four', 'five']

 

splice

  • 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경
  • 매개변수1(optional) : start. 배열의 변경을 시작할 인덱스
  • 매개변수2(optional) : deletecount. 배열에서 제거할 요소의 수
  • 매개변수3(optional) : item1, item2, ... 배열에 추가할 요소. 아무 요소도 지정하지 않으면 splice()는 요소를 제거하기만 한다.
  • 반환값 : 제거한 요소를 담은 배열. 하나의 요소만 제거한 경우 길이가 1인 배열을 반환. 아무 값도 제거하지 않았으면 빈 배열을 반환.
  • 사용 예시)
const months = ['Jan', 'March', 'April', 'June'];

months.splice(1, 0, 'Feb');
console.log(months);
// 결과: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
console.log(months);
// 결과: Array ["Jan", "Feb", "March", "April", "May"]

 

 

Array.isArray()

  • 메서드 인자가 Array인지 판별. 
  • 매개변수1(optional) : obj. 검사할 객체
  • 반환값 : 객체가 Array라면 true를 반환하고 아니면 false를 반환한다.
  • 사용 예시)
Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar');   // false
Array.isArray(undefined);  // false

 

 

push()

  • 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환
  • 매개변수1(optional) : elementN. 배열의 끝에 추가할 요소
  • 반환값 : 메서드를 호출한 배열의 새로운 length 속성.
  • 사용 예시)
const animals = ['pigs', 'dogs', 'sheep'];

const count = animals.push('cows');
console.log(count);
// 결과 : 4

console.log(animals);
// 결과 : Array ['pigs', 'dogs', 'sheep', 'cows']

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// 결과 : ['pigs', 'dogs', 'sheep', 'cows', 'chickens', 'cats', 'dogs']

 

 

unshift()

  • 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환
  • 매개변수1(optional) : elementN. 배열의 맨 앞에 추가할 요소
  • 반환값 : 메서드를 호출한 배열의 새로운 length 속성.
  • 사용 예시)
const array = [1, 2, 3];

console.log(array.unshift(4, 5));
// 결과 : 5

console.log(array);
// 결과 : Array [4, 5, 1, 2, 3]

 

 

pop()

  • 배열에서 마지막 요소를 제거하고 그 요소를 반환
  • 반환값 : 배열에서 제거한 요소. 빈 배열의 경우 undefined를 반환
  • 사용 예시)
const plants = ['broccoli', 'carrot', 'cabbage', 'kale', 'tomato];

console.log(plants.pop());
// 결과 : tomato

console.log(plants);
// 결과 : Array ['broccoli', 'carrot', 'cabbage', 'kale']

plants.pop();

console.log(plants);
// 결과 : Array ['broccoli', 'carrot', 'cabbage']

 

shift()

  • 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환. 이 메서드는 길이를 변하게 한다.
  • 반환값 : 배열에서 제거한 요소. 빈 배열의 경우 undefined를 반환
  • 사용 예시)
const array = [1, 2, 3];

const firstElement = array.shift();

console.log(array);
// 결과 : Array [2, 3]

console.log(firstElement);
// 결과 : 1

 

indexOf()

  • 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하며 존재하지 않으면 -1을 반환.
  • 문자열도 해당 메서드를 적용할 수 있다.
  • 매개변수1 : searchElement. 배열에서 찾을 요소
  • 매개변수2(optional) : fromindex. 검색을 시작할 색인. 인덱스가 배열의 길이보다 크거나 같은 경우 -1이 반환되므로 배열이 검색되지 않는다. 색인 값이 음수면 배열 끝에서부터의 오프셋 값으로 사용되며, 배열은 여전히 앞에서 뒤로 검색된다. 기본값은 0이다.
  • 반환값 : 배열 내의 요소의 최초의 인덱스. 발견되지 않으면 -1을 반환.
  • 사용 예시)
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// 결과 : 1

console.log(beasts.indexOf('bison', 2));
// 인덱스 2번부터 시작한다.
// 결과 : 4

console.log(beasts.indexOf('giraffe'));
// 결과 : -1

 

includes()

  • 배열이 특정 요소를 포함하고 있는지 판별.
  • 매개변수1 : valueToFind. 탐색할 요소
  • 참고: 문자나 문자열을 비교할 때, includes()는 대소문자를 구분한다.
  • 매개변수2(optional) : fromindex. 배열에서 검색을 시작할 위치. 음수일 경우 array.length + fromIndex의 인덱스를 asc로 검색하며 기본값은 0이다.
  • 반환값 : Boolean
  • 사용 예시)
const array = [1, 2, 3];

console.log(array.includes(2));
// 결과 : true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// 결과 : true

console.log(pets.includes('at'));
// 결과 : false