배열 (Array) & 배열의 메서드

summerlee·2022년 9월 12일
0

TIL

목록 보기
8/39

배열(Array)

  • 특정한 데이터들을 일정하게 일렬로 모아놓은 집합
  • 배열은 값의 집합
  • 배열은 값의 순서 있는 집합
	let myArray = [19, 44, 'good', false]
  • 배열 안에 들어있는 값들은 요소(element) 라고 부른다.
    ex) 19는 myArray 라는 배열의 요소 중 하나이다.

  • 배열에는 순서가 있다 index 넘버를 기준으로 0부터 시작한다.
  • 요소에 접근한다는 것은, 특정한 배열에 들어있는 요소 하나에 대한 작업진행을 위해 요소 하나를 가져오는 행위를 의미한다. ---> 이때 Index 넘버를 사용!
	let myArray = [19, 44, 'good', false]

	let first = myArray[2]
    
    console.log(first);

	// -----> 결과: good

배열의 요소 변경(수정) 하기

	let myArray = [19, 44, 'good', false]
	myArray[0] = "hello";
    console.log(myArray);
	// -----> 결과: ["hello", 44, "good", false]

배열의 길이 구하기 /

.length

	let myArray = [19, 44, 'good', false]
    console.log(myArray.length)   // myArray의 길이를 콘솔에 찍으라는 뜻
	// -----> 결과: [4]

배열의 요소 추가하기

1. .push( )

  • 배열의 마지막 요소 뒤에 하나 이상의 요소 추가 가능
  • 인수 필요
	let myArray = [19, 44, 'good', false]
    myArray.push(300);   // 마지막 요소 뒤에 300이라는 요소 추가
    console.log(myArray)
	// -----> 결과: [19, 44, 'good', false, 300]

2. .unshift( )

  • 배열의 첫번째 요소 추가
	let myArray = [19, 44, 'good']
    myArray.shift();   // 첫번째 요소 삭제
    console.log(myArray)
	// -----> 결과: [44, 'good']

배열의 요소 삭제하기

1. .pop( )

  • 배열의 마지막 요소 제거
  • 인수 필요 x
	let myArray = [19, 44, 'good', false]    
    myArray.pop();   // 마지막 요소 삭제
    console.log(myArray)
	// -----> 결과: [19, 44, 'good']

2. .shift( )

  • 배열의 첫번째 요소 제거
	let myArray = [19, 44, 'good']
    myArray.shift();   // 첫번째 요소 삭제
    console.log(myArray)
	// -----> 결과: [44, 'good']

이렇게 .push, .pop, .shift, .unshift 등 을 Array의 메소드(메서드) 라고 부른다.


더 많은 배열 메서드 알아보기

.concat( )

  • 2개의 배열을 합쳐서 새 문자열(제 3의 배열)을 만드는 것
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// 결과:  Array ["a", "b", "c", "d", "e", "f"]

.includes( )

  • boolean 메서드의 예시로 true나 false로 응답한다.
  • 배열에 특정 값이 포함되어 있는지 알려준다.
const array1 = ['1', '2', '3'];

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

const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('rabbit'));
// 결과:  false

.reverse( )

  • 배열을 뒤집어 준다.
  • 원본을 바꿔버리기 때문에 파괴 메서드라고도 알려져 있다.
const array1 = ['one', 'two', 'three'];
console.log(array1);
// 결과: Array ['one', 'two', 'three']

const reversed = array1.reverse();
console.log(reversed);
// 결과:  Array ['three', 'two', 'one']

console.log(array1);
// 결과:  Array ['three', 'two', 'one']
// 단순히 사본이 뒤집힌 것이 아닌, 이렇게 원본을 바꿔버린다.

.slice( )

  • 배열의 일부를 복사하는 방법
  • .slice(start, end)
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant];

console.log(animals.slice(2));
// 결과: Array ['camel', 'duck', 'elephant']
// start 값만 적으면 start 값부터 배열 끝까지 출력

console.log(animals.slice(2, 4));
// 결과: Array ['camel', 'duck']
// start, end 값 둘다 적으면 start 값부터 end 값의 한단계 이전 값까지 출력된다. end 값은 새롭게 출력되는 값에 포함되지 않는다.

.splice( )

  • 기존 요소들을 제거하거나 대체하거나 새로운 요소들을 추가해서 배열의 내용을 변경한다.
  • 원래 배열 자체를 변경하며 복사본을 만들지 않는다.
  • 사용 빈도 낮음
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// months.splice(시작할인덱스(추가할 위치의 인덱스), 제거할인덱스, 추가할요소);
// 추가할요소 생략 가능(제거만 한다면)

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

.sort( ) // 나중에 다시 공부 후 정리

  • 배열을 정렬하는 메서드
  • 숫자를 예로 들었을 때, 숫자 크기별로 정렬을 하긴 하는데 첫번째 자리의 숫자만 계산해서 정렬함..(조심)
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// 결과: Array ["Dec", "Feb", "Jan", "March"]

중첩된 배열

	let myArray = [19, 44, 'good',[100, 200], false]
    // 이러한 경우, [100, 200] 은 하나의 요소로 인정되어 3번째 인덱스 넘버가 된다.
    
    console.log(myArray[3])
	// myArray 배열의 3번째 인덱스 넘버를 콘솔창에 띄우겠다.
	// ----> 결과 : [100, 200]

	console.log(myArray[3][0])
	// myArray 배열의 3번째 인덱스 넘버의 0번째 인덱스 넘버를 콘솔창에 띄우겠다.
	// ----> 결과 : 100
  • 여기서 [3]번째 인덱스 넘버를 띄웠을 때, [100, 200]이 나왔는데, [3]번째의 [0]번째 인덱스 넘버를 띄우니 [100]이 아닌 100이 나왔다.

  • 이처럼 대괄호가 사라진 이유는, 처음 띄웠을 땐 배열 속의 배열 그 자체, 즉 중첩된 배열이었던
    [100, 200] 이라는 요소가 [3]번 인덱스 자체로 출력되어 나온 것이고,

  • 두번째 콘솔을 띄웠을 땐 요소 자체가 배열이기 때문에 다시한번 [3]번 인덱스의 [0]번 인덱스에 접근해서(배열의 배열속으로 접근) 값만 띄운것이기 때문이다.

profile
완벽하지 않아도 기록하려고 노력하기 😅

0개의 댓글