[TIL] 2. Javascript Array Method

ILYSB·2021년 6월 11일
0

[Today I Learned]

목록 보기
2/3

javascript array에서 자주쓰이는

메소드에 대해서 포스팅하겠습니다.



1. push : add an item to the end

=> 배열의 마지막에 date를 추가한다.

const fruits = ['사과', '바나나','망고'];

ex) fruits.push('딸기','복숭아');
    
    console.log(fruits); 
  
  => ['사과', '바나나', '망고', '딸기', '복숭아'];

2. pop : remove an item from the end

=> 배열의 마지막에 있는 data 를 제거한다.

const fruits = ['사과', '바나나', '망고', '딸기', '복숭아'];

fruits.pop();
fruits.pop();
fruits.pop();

console.log(fruits); 

=> ['사과', '바나나']
  
pop 메소드를 3번 사용하여 마지막 데이터 3개를 제거한다

3. unshift : add an item to the beginning

=> 배열의 처음에 data를 추가한다.

const fruits = ['사과', '바나나']

fruits.unshift('딸기', '레몬'); 

console.log(fruits);

=>['딸기', '레몬', '사과', '바나나']

4. shift : remove an item to the beginning

=> 배열의 처음 data를 제거한다.

const fruits = ['딸기', '레몬', '사과', '바나나']

fruits.shift();
fruits.shift();

console.log(fruits);

=> ['사과', '바나나'] 

5. splice : remove an item by index position

=> 첫번째 파라미터(매개변수)는 data를 제거하기 시작하는 첫번째 인덱스이며 두번 째 파라미터는 몇개의 data를 제거할 것인지를 의미하는 숫자이다.
또한 제거한 data 인덱스 자리에 새로운 data를 추가할수있다.

const fruits = ['사과', '바나나','망고'];

fruits.splice(0,1);

console.log(fruits);

=> ['바나나','망고'];
const fruits = ['사과', '바나나','망고'];

fruits.splice(0,1,'수박','딸기');

console.log(fruits);
=> ['수박', '딸기', '바나나','망고'];

6. concat : combine two arrays

=> 두개의 배열을 합친다.

const frurit =['사과', '수박']

const fruits2 =['모과' , '배'];

const newFruits = fruits.concat(fruits2);

console.log(newFruits);

['사과', '수박', '모과' , '배']

7. indexOf : serching find the index

=> data의 인덱스를 알수있다.

const fruits = ['사과', '바나나', '딸기'];             

console.log(fruits.indexOf('딸기'));  

=> 2

8. includes : 배열이 data를 포함하는지 boolean으로 출력한다.

const fruits = ['사과', '바나나', '딸기'];   

console.log(fruits.includes('딸기'));

=> true

9. lastIndexOf : data가 마지막으로 속해있는 index를 알려준다.

const fruits = ['사과', '딸기', '바나나', '딸기'];

console.log(fruits.lastIndexOf('딸기'));

=> 3

출처 : 드림코딩

profile
💻

0개의 댓글