🦎 JavaScript

[JS] 배열 매서드(Array methods)

하나둘세현 2023. 2. 27. 01:04
728x90

배열 매서드(Array methods) 

→ 연산이라고 생각하면 쉽다. 

Js에서 기본 제공 함수들이 있는데 기본적으로 배열에 직접 적용할 수 있다. 그것들을 배열 매서드라고 부른다. 


const friends = ["Michael", "Steve", "Peter"];

push

push 매서드는 배열의 끝에 요소들을 추가한다.

const friends = ["Michael", "Steve", "Peter"];
friends.push("Jay");

친구를 입력하고 .push를 하면 배열 끝에 요소들을 추가한다. push는 본질적으로 함수이다. 옆에 괄호가 있다. 괄호는 우리가 호출하는 함수이다. push앞에 있는 .은 friends배열 자체에 연결되는 함수인걸 의미한다. 

 

● push는 메서드이다.

● 기술적으로 함수이다. 

 

push 함수는 freinds 배열에 연결되어 있다. 

const friends = ["Michael", "Steve", "Peter"];
friends.push("Jay");
console.log(friends);

 

배열 마지막에 Jay가 출력된것을 확인할 수 있다.

 

push는 함수이기 때문에 뭔가를 return할 수도 있다. (← 함수안에 인자를 전달 할 수 있다.)  이미 Jay한테 인자를 전달했다.

그럼 함수가 어떤 일을 할 수 있을까????????

함수가 하는 일은 요소를 배열에 추가하는 거다. 사실 push함수는 값을 반환한다. 반환하는 값은 새 배열의 길이이다.

해당 데이터나 값을 캡처하고 싶다면 새 변수를 생성할 수 있다. ← 어떻게?

이렇게 ↓ 

const friends = ["Michael", "Steve", "Peter"];
const newLength = friends.push("Jay");
console.log(friends);

const friends = ["Michael", "Steve", "Peter"];
const newLength = friends.push("Jay");
console.log(friends);
console.log(newLength);

newLength라고 하고 큰솔에 로그인했다.

보통은 요소 하나를 push하고 그걸로 끝낸다. 새 배열의 길이가 즉시 필요한것은 아니기때문이다.  

하지만 필요한 경우에는 따로 계산할 필요가 없다. push함수의 결과를 가져다가 변수에 저장하고 사용하면 된다. 


unshift 

배열 시작에 요소를 추가하는 메서드가 있다. 그것은 unshift 메서드라고 한다.

friends.unshift("John");
console.log(friends);

friends배열의 시작 부분에 John을 추가하고 싶었다. 그래서 friends.unshift("John")을 입력했다. push 메서드 처럼 unshift 메서드도 새 배열의 길이를 리턴한다. 하지만 이 경우에는 저장하지 않는다. 왜냐면? 필요하지 않으니까 


pop

배열에서 요소를 제거하는 메서드. push 메서드와 반대이다. pop은 배열의 마지막 요소를 제거한다. 

 

friends.pop();

인수를 넘길 필요가 없다. 마지막 요소를 제거하는데 정보가 필요없기 때문이다. 

friends.pop();
console.log(friends);

결과는 어떻게 나올까?

Jay가 사라졌다. 

그럼 만약에 freinds.pop()을 두번적는다면 Jay도 사라지고,, Peter 역시 사라질까?

friends.pop();
friends.pop();
console.log(friends);

그렇다. Peter와 Jay가 사라졌다. 

pop메서드도 역시 뭔가를 반환하지만 이건 새 벼열의 길이를 반환하지 않는다. 대신에 제거된 요소를 반환한다.

friends.pop();
const popped = friends.pop();
console.log(popped);
console.log(friends);

pop요소는 peter가 될것이다. 

첫번째에서는 Jay, 두번째에서는 Peter가 된다. 

friends.pop(); → Jay 제거
const popped = friends.pop();  → Peter 제거(를 해서 제거된 요소를) popped 변수에 저장되는 요소이다. 
console.log(popped); → Peter 출력된것을 사진에서 볼 수 있삼
console.log(friends);

 

shift

friends.shift(); //frist
console.log(friends);

인수가 필요없다. shift메서드는 제거된 요소를 반환할 것이다. 필요한 경우 저장할 수 있다. 


.indexOf

배열의 특정 요소가 어느 위치에 있는지 알려주는 메서드

console.log(friends.indexOf("Steve"));
console.log(friends.indexOf("Bob"));

큰솔에 로그인해서 friends.indexOf를 작성하고 요소를 전달하면 된다.(즉 참조하고 싶은 것들을 말이다.)

console.log(friends.indexOf("Steve")); → 옆 코드를 보면 스티븐을 원한다. 이 요소가 위치한 인덱스를 반환해야 한다.

지금은 steve가 1번이다.  0은 Michael, 1은 Steve이다. 함수 호출은 값을 1로 반환해야 한다. 스티븐이라는 요소의 indexOf이니까. 그래서 오른쪽 사진의 출력 결과에 1이 나온거다. 

만일 거기에 없는 요소를 입력하면? 그러니까 Bob이라는 사람을 입력하면? -1이 나온다. 

 

includes

indexOf와 비슷한 방법 

더 현대적이고 더 유용한 방법이다. 이건 ES6 메서드로 "includes" 불린다. 

요소의 인덱스를 반환하는 대신 요소가 배열 안에 있으면 참을 반환하고 그렇지 않으면 거짓을 반환한다.

console.log(friends.includes("Steve"));
console.log(friends.includes("Bob"));

Steve는 참으로 나오고 

Bob은 거짓으로 나왔다. 

Steve는 요소에 있지만 Bob은 없기 때문이다. 

 

만일 23을 freinds요소에 push를 하게 되면 출력은 어떻게 될까?

friends.push(23);
console.log(friends.includes("Steve"));
console.log(friends.includes("Bob"));
console.log(friends.includes("23"));

문자열을 출력했음으로 false가 나왔다. 이것은 엄격한 평등 테스트이다. 문자열 23은 숫자와 다르기때문에 거짓이 나왔다. console.log(friends.includes(23)); 이 경우에는 true가 나온다. 숫자를 출력했기 때문이다. 

 

include메서드를 사용해 조건을 작성할 수 있다. 이 메서드의 아주 유용한 응용 프로그램 중 하나이다.  

if (friends.includes("Peter")) {
  console.log("You have a friend called Peter");
}

if (friends.includes("Peter")) { → 부울 값을 반환한다. 
  console.log("You have a friend called Peter");
}

이 배열에 Peter와의 문자열을 포함하면 이 코드는 그때만 실행된다. 

Peter 자리에 Steve가 있다면???

 

if (friends.includes("Steve")) {
  console.log("You have a friend called Steve");
}

출력되낟. 

728x90