Array | Method

이선호·2021년 8월 7일

Javascript

목록 보기
6/8

배열의 Method

let myArray = ['a', 'b', 'c', 'd'];

push() & pop()

push pop은 각각 배열의 끝에 요소를 추가하거나 제거한다.

myArray.push('e') // 결과 : myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.pop() // 결과 : myArray = ['a', 'b', 'c'];

unshift() & shift()

unshift shift는 각각 배열의 처음에 요소를 추가하거나 제거한다.

myArray.unshift('e') // 결과 : myArray = ['e','a', 'b', 'c', 'd'];
myArray.shift() // 결과 : myArray = ['b', 'c', 'd'];

slice()

  • 원본 배열에서 요소의 일부를 복사해서 반환한다.
  • 원본 배열은 유지
  • 음수를 쓰면 배열의 끝에서 부터 요소를 센다.
myArray.slice(2) // 결과 : ['c', 'd'];
myArray.slice(1,3) // 결과 : ['b', 'c'];
myArray.slice(-2) // 결과 : ['c', 'd'];

splice()

  • 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경할 수 있다.
  • 원본손상
  • 첫 번째 매개변수는 수정을 시작할 인덱스
  • 두 번째 매개변수는 제거할 요소
  • 아무 요소도 제거하지 않을 때는 0을 넘기고 나머지 매개변수는 배열에 추가될 요소이다.

myArray.splice(start[, deleteCount[,item1[,item2[..])

//ex)
myArray.splice(1, 0, 'ABC');
//  결과 : Array ['a', 'ABC', 'b', 'c', ''d]

concat()

concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);  
-------------------
console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

forEach()

forEach() 주어진 함수를 배열 요소 각각에 대해 실행합니다.

myArray.forEach(function(element) {
  console.log(element);
}); // 결과: a, b, c, d

map()

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

const array1 = [10, 40, 90, 160];
// pass a function to map
const map1 = array1.map((x) => x * 10);
-----------------
console.log(map1);
// expected output: Array [100, 400, 900, 1600]

filter()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

  • 조건에 만족하는 요소들로만 구성된 새로운 배열을 리턴한다.
  • 조건에 부합되는 요소가 없다면 빈 배열을 반환한다.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

indexOf()

indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.

  • 배열 안에서 찾으려는 값과 일치하는 '첫번째' 요소의 인덱스(위치)를 리턴합니다.
  • 중복되는 요소중 원하는 요소가 뒤에 있을땐 일치하는 요소의 번째수를 써준다. (인덱스 번호아님)
  • 배열에 없는 요소를 찾을땐 -1을 반환한다.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1

includes()

includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.

  • 배열 속 해당 요소가 있으면 true, 없으면 false를 반환한다.
  • 배열.includes(찾는 요소 [, fromIndex])
const array1 = [1, 2, 3];
------------------------
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false

🧐 참고사이트

0개의 댓글