상세 컨텐츠

본문 제목

코드카데미 Javascript - 배열 메서드 (push, pop, shift, slice, indexOf)

IT/Javascript

by J KIMS 2020. 9. 23. 11:17

본문

반응형

Array

- 배열은 [] 을 이용해서 선언한다

- 어떤 종류의 데이터 타입도 담을 수 있음

- 데이터 타입이 다른 종류를 섞어서 배열에 넣는 것도 가능함 (하지만 추천은 하지 않음..)

- 배열에 접근할 때는 인덱스를 이용함. 배열의 인덱스는 0부터 시작하고 범위를 벗어난 값에 접근하려고 하면 undefined 이 표시됨

 

const hobbies = ['Playing Guitar', 'Blog', 'Watching Netflix'];

console.log(hobbies);

console.log(hobbies[0]); //Playing Guitar
console.log(hobbies[3]); //undefined

 


const vs let

- let으로 선언한 배열은 배열의 값을 수정하는 것도 새로운 배열을 할당하는 것도 모두 가능하다

- const로 선언한 배열은 값을 바꾸는 건 가능하지만 새로운 배열을 할당하는 것은 불가능하다 (TypeError)

 

let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];

const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];

// 배열의 값을 수정
condiments[0] = 'Mayo';
console.log(condiments); // [ 'Mayo', 'Mustard', 'Soy Sauce', 'Sriracha' ]

// 배열에 새로운 배열 할당
condiments = ['Mayo'];
console.log(condiments); // [ 'Mayo' ]

// 배열의 값을 수정
utensils[3] = 'Spoon';
console.log(utensils); // [ 'Fork', 'Knife', 'Chopsticks', 'Spoon' ]

length

- 배열의 이름에 .length를 붙이면 배열의 크기를 알 수 있다

 

const objectives = ['Learn a new languages', 'Read 52 books', 'Run a marathon'];

console.log(objectives.length); // 3

💡 배열 메서드 Tip. 원래의 배열을 변형시키는지, 어떤 값을 리턴하는지에 주목

push( ) 

- 푸쉬 메서드는 배열의 끝에 값을 집어 넣는다

- 또한 초기 배열의 형태도 바꾼다 (mutate)

 

const chores = ['wash dishes', 'do laundry', 'take out trash'];

chores.push('clean room', 'refill water bottle');

console.log(chores);
// 출력결과 : [ 'wash dishes','do laundry','take out trash','clean room','refill water bottle' ]

 

pop( )

- 팝은 배열의 마지막 값을 제거하고 리턴한다

 

const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook dinner', 'mop floor'];


chores.pop();
console.log(chores);
// 출력 결과 : [ 'wash dishes', 'do laundry', 'take out trash', 'cook dinner' ]
 

shift( )  vs unshift( )

- shift는 배열의 첫번째 값을 제거하고 제거된 값을 리턴함

- 이 메서드는 배열의 길이를 바꿈

 

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

 

▶ MDN 문서보기

 

- unshift는 배열의 첫번째에 값을 대입하고 새로운 배열의 길이를 리턴함

 

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

 

▷ MDN 문서보기

 


slice( )

- slice(start, end)

- start와 end는 배열의 인덱스를 나타냄

- slice는 start부터 end까지의 값들을 복사해서 리턴함. 이때, end의 값은 포함하지 않음.

- slice는 원래의 배열을 변형시키지 않음 (un-mutating)

 

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

 

▷ MDN 문서보기


splice( )

- splice(시작 인덱스, 삭제할 요소 수, 대입할 값)

- splice는 원래의 배열을 변형시키는 메서드

- 지정한 인덱스부터 지정한 수 만큼 요소를 삭제하고 다른 값으로 대체할 수 있음

 

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

 

▷ MDN 문서보기


indexOf( )

- indexOf(searchElement, fromIndex)

- 배열에 찾는 값이 포함되어 있으면 그 값에 해당하는 인덱스를 리턴함

- 배열의 처음부터 서치를 시작해서 가장 처음 발견된 인덱스를 리턴함

- 어디서부터 서치를 시작할지 정할 수 있음

- 만약 찾는 값이 발견되지 않으면 -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

 

▷ MDN 문서보기


join( )

- join(구분자)

- 문자열들을 지정한 구분자로 연결해서 리턴함

 

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

 

▷ MDN 문서보기


Nested Arrays

- 배열의 요소들을 괄호[]로 묶은 것

- 묶어진 값들은 하나의 요소로 취급되며 그 안의 값에 접근할 때는 2차원 배열과 같은 방식을 씀

 

const numberClusters = [[1,2],[3,4],[5,6]];
const target = numberClusters[2][1];

 

numberClusters는 세 가지 요소로 구성된 배열이다.

target에는 6이 저장되어있다.

반응형

관련글 더보기

댓글 영역