TIL 02. Array의 methods

Drageon Lee·2021년 9월 6일
1

Array

Array란?

  • 프로토타입으로 탐색과 변형 작업을 수행하는 메서드를 갖는, 리스트와 비슷한 객체입니다. Array 내 value를 element(요소)라고 부르며, 각 element들은 각각의 index(순서)를 가짐.
  • ['Javascript', 'Python',...] 형태로 나타냄

Methods in array

1. 제거

pop

→ 배열의 끝항목 부터 제거

Array.pop()
ex)
let fruits = ['banana', 'apple', 'orange', 'grape', strawberry']
fruits.pop()
console.log(fruits)
//['banana', 'apple', 'orange', 'grape']

shift

→ 배열의 앞 항목 부터 제거

Array.shift()
ex)
let fruits = ['banana', 'apple', 'orange', 'grape', strawberry']
fruits.shift()
console.log(fruits)
//['apple', 'orange', 'grape', 'strawberry']

slice

→ 배열 내 특정 구간의 요소들을 원본 배열의 변형 없이 리턴함

Case 1) 두개의 인자가 들어갈 경우
Array.slice(start index, end index)
→ Start index에서 end index 바로 앞 요소 까지 return
ex)
let fruits = ['banana', 'apple', 'orange', 'grape', strawberry']
console.log(fruits.slice(1,3))
// ['apple', 'orange']

Case 2) 1개의 인자만 들어갈 경우
Array.slice(index)
→ 해당 index 앞 쪽의 요소는 제외하고 return
ex)
let fruits = ['banana', 'apple', 'orange', 'grape', 'strawberry']
console.log(fruits.slice(2))
// ['orange', 'grape', 'strawberry]

splice

→ splice는 배열 내의 특정한 요소를 삭제하거나, 다른 요소로 대치하거나 새로운 요소를 추가할 때 사용

Array.splice(start index, item number for remove, replaced item)
Case 1) replaced item이 없을 경우
let fruits = ['banana', 'apple', 'orange', 'grape', 'strawberry']
fruits.splice(2,1)
console.log(fruits)
//let fruits = ['banana', 'apple', 'grape', 'strawberry']

Case 2) replaced item이 있을 경우
let fruits = ['banana', 'apple', 'orange', 'grape', 'strawberry']
fruits.splice(2,1,'blueberry')
console.log(fruits)
//['banana', 'apple', 'blueberry', 'grape', 'strawberry']

2. 추가

push

→ 요소를 추가할 때 사용(배열 끝 쪽에 요소가 추가 됨)

Array.push('kiwi')
ex)
let fruits = ['banana', 'apple', 'orange', 'grape', 'strawberry']
fruits.push('kiwi')
console.log(fruits)
//['banana', 'apple', 'orange', 'grape', 'strawberry', 'kiwi']

unshift

→ 배열 맨 앞쪽에 요소 추가 할 때 사용

Array.unshift('kiwi')
ex)
let fruits = ['banana', 'apple', 'orange', 'grape', 'strawberry']
fruits.unshift('kiwi')
console.log(fruits)
//['kiwi', 'banana', 'apple', 'orange', 'grape', 'strawberry']

concat

→ 주어진 배열에 기존 배열을 합쳐서 새로운 배열을 return

Array.concat(Array1)
ex)
let fruits = ['banana', 'apple', 'orange', 'grape', 'strawberry']
let vegetables = ['tomato', 'cabbage', 'potato']
let fruitveg=fruits.concat(vegetables)
console.log(fruitveg)
//['banana', 'apple', 'orange', 'grape', 'strawberry', 'tomato', 'cabbage', 'potato']

이번 TIL에서는 배열의 method에 대해서 정리하였습니다.

!! 수정이 필요한 사항에 대해서는 댓글 주시면 감사하겠습니다.!!

참고자료 : MDN 자료

꾸준히 업데이트하고 업로드 하는 발전하는 개발자가 되기 위해...

profile
운동하는 개발자

0개의 댓글