javascript - array(배열)

bebrain·2022년 11월 11일
0

배열의 선언방법

첫번째 방법(생성자함수식)

const arr1 = new Array(1, 2, 3, 4, 5)

Array라는 클래스를 활용해서 객체를 만들었다고 생각하면 된다.
Array라는 클래스를 선언한 적은 없지만 자바스크립트 내부적으로 이미 갖고 있기 때문에 우리는 바로 사용만 하면 되는것.

두번째 방법(변수식)

const arr2 = [1, 2, 3, 4, 5]

배열을 바로 만드는 방법.
대개 이 방법을 사용한다.

배열의 구조

const rainbowColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

배열요소 호출방법

console.log(rainbowColors[0]) // o번 인덱스를 통해서 데이터에 접근 = red
console.log(rainbowColors[1]) // 1번 인덱스를 통해서 데이터에 접근 = orange
console.log(rainbowColors[2]) // 2번 인덱스를 통해서 데이터에 접근 = yellow
console.log(rainbowColors[3]) // 3번 인덱스를 통해서 데이터에 접근 = green
console.log(rainbowColors[4]) // 4번 인덱스를 통해서 데이터에 접근 = blue
console.log(rainbowColors[5]) // 5번 인덱스를 통해서 데이터에 접근 = indigo
console.log(rainbowColors[6]) // 6번 인덱스를 통해서 데이터에 접근 = violet

배열길이

const rainbowColors = [
	'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'
]

console.log(rainbowColors.length) // 7

배열의 마지막 요소 찾기(length 활용)

const rainbowColors = [
	'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'
]

console.log(rainbowColors[rainbowColors.length - 1]) // violet

배열의 메소드 종류

배열에 요소 추가/삭제

배열의 마지막 요소 - push, pop

const rainbowColors = [
	'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'
]

rainbowColors.push('ultraviolet') // 배열의 마지막에 ultarviolet 추가
console.log(rainbowColors) // ultraviolet이 추가된 rainbowColors 출력

rainbowColors.pop() // 배열의 마지막 요소 ultraviolet을 제거
console.log(rainbowColors) // ultraviolet이 제거된 rainbowColors 출력

배열의 첫번째 요소 - unshift, shift

const rainbowColors = [
	'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'
]

rainbowColors.unshift('white') // 배열의 첫번째에 white 추가
console.log(rainbowColors) // white이 추가된 rainbowColors 출력

rainbowColors.shift() // 배열의 첫번째 요소 white을 제거
console.log(rainbowColors) // white이 제거된 rainbowColors 출력

다른 배열 추가하기 - concat

const rainbowColors = [
	'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'
]

const result = rainbowColors.concat(['white'],['black'],['A','B'])
console.log(result) // ['red'... 'violet', 'white', 'black', 'A', 'B']

배열의 요소 순서 뒤집기

const rainbowColors = [
	'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'
]

rainbowColors.reverse()
	// ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red']

요소로 인덱스번호 찾기 - indexOf()

const rainbowColors = [
	'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'
]

rainbowColors.indexOf('green')
console.log(result) // 3

map(콜백함수) - 콜백함수식을 배열의 모든 요소에 적용시켜 새로운 배열을 return

const rainbowColors = [
	'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'
]

const result = rainbowColors.map(function(arr){
    return arr + 'A'
})
console.log(result) // [
  'redA',    'orangeA',
  'yellowA', 'greenA',
  'blueA',   'indigoA',
  'violetA'
]

0개의 댓글