.png)
오늘은 velopert님의 강의 자료를 활용하여 JavaScript에 배열과 내장함수에 대해서 공부해보도록 하겠습니다.
자바스크립트의 배열에는 여러가지 항목들을 담을 수 있습니다.
EX ) 객체 , 숫자 , 문자 , etc ..
배열을 생성 할 때에는 리스트 형태로 [] 감싸주면 됩니다.
const arr = [1, 'blabla' , {name:'hp'}];
자바스크립트에서 값을 추가하거나 추출할 때는 아래와 같은 내장함수를 이용합니다.
배열 내장함수
const arr = [1, 'blabla' , {name:'hp'}];
arr.push(5);
console.log(arr); // [1, 'blabla' , {name:'hp'} , 5];
// pop 메소드는 값을 추출해서 변수에 담을 수 있다.
const popItem = arr.pop();
console.log(popItem) // 5
console.log(arr); // [1, 'blabla' , {name:'hp'}]
push 와 pop 은 배열의 가장 오른쪽에 추가하고 추출하는 메소드인 반면 unshift와 shift는 배열의 가장 왼쪽에 값을 추가하고 추출합니다.
배열 내장함수
const arr = [1, 'blabla' , {name:'hp'}];
arr.unshift(5);
console.log(arr); // [5, 1, 'blabla' , {name:'hp'}]
// shift 메소드도 pop 메소드와 같이 추출해서 변수에 담을 수 있다.
const shiftItem = arr.shift();
console.log(shiftItem); // 5
console.log(arr); // [1, 'blabla' , {name:'hp'}]
splice는 특정 항목을 제거할 때 사용하는 내장함수입니다.
pop메소드와 다른점은 index를 활용하여 인덱스를 기준으로 몇개를 지울지를 정할 수 있습니다.
배열 내장함수
slice는 splice와 다르게 기존의 배열을 건들지 않는다.
예제를 보기에 앞서 자바스크립트에서 index 값을 찾는 함수에는 indexOf와 findIndex 함수가 있습니다.
배열 내장함수
만일 배열안에 있는 값이 숫자 , 문자열 , boolean이라면 찾을 수 있지만 객체나 배열이면 찾을 수 없습니다.
그래서 우리는 findIndex 를 사용합니다.
arr.findIndex(함수)
findIndex는 파라미터로 함수를 입력받아 , 특정 조건을 확인해서 조건을 만족하면 만족하는 원소가 몇 번째인지 알려주는 함수입니다.
findIndex 메서드는 해당 조건에 만족하는 첫번째 요소의 인덱스를 반환합니다.
indexOf와findIndex모두 값이 존재하지 않으면 -1을 반환합니다.
const arr = [1, 'blabla' , {name:'hp'}];
const idx1 = arr.indexOf(1);
const idx2 = arr.indexOf('blabla');
const idx3 = arr.findIndex(obj => obj.name === 'hp');
console.log(idx1); // 0
console.log(idx2); // 1
console.log(idx3); // 2
const arr = [1, 'blabla' , {name:'hp'}];
const idx = arr.indexOf(1); // 0
const result = arr.splice(idx , 2);
console.log(result); //[1, 'blabla']
console.log(arr); // [{name:'hp'}]
const arr = [1, 'blabla' , {name:'hp'}];
const sliced = arr.slice(0,2);
console.log(sliced); // [ 1, 'blabla' ]
console.log(arr); // [ 1, 'blabla', { name: 'hp' } ]
끝까지 읽어주셔서 감사합니다. 😁