본문 바로가기

html+CSS+JS

스터디 일지 | HTML, CSS, jQuery 어중간한 초급자 탈출하기 #9 - 배열, 배열 메소드(splice, indexOf, shift,pop,push,unshift 등)

반응형
#9회차 (사실 복습을 안 해서 내용이 훅 건너뜀... 가능하면 나중에 복습하겠소...)
배열과 배열 관련 메소드

 

1) 배열

- 객체 중 하나. 값들의 나열을 한번에 저장하는 종류의 객체. index(순서)를 요소 name처럼 사용 가능

let emotion = ['love', 'like', 'dislike', 'hate', 'happiness', 'sadness'];

console.log(emotion[0]); // love
console.log(emotion[4]); // happiness

* index는 0부터 세기 때문에 0번째, 1번째, 2번째 순서라고 생각하면 편하다.

 

 

2) 배열 메소드

- 요소 추가&제거 메소드: splice(startIndex, deleteCount, item)

: startIndex부터의 요소를 deleteCount 개수만큼 지우고, item(요소)를 추가한다.

let clothes = ['shirts', 'dress', 'suit', 'skirt', 'pants', 'cardigan'];

clothes.splice(4);
console.log(clothes); // [shirts, dress, suit, skirt]

clothes.splice(1, 1);
console.log(clothes); // [shirts, suit, skirt]

clothes.splice(0, 1, 'scarf', 'shoes');
console.log(clothes); // [scarf, shoes, suit, skirt]

startIndex = 필수

deleteCount = 선택 (없으면 startIndex부터 맨 끝 요소까지 전부 삭제)

item = 선택 (deleteCount까지 쓰고 써야함. 없으면 요소 추가 없음)

 

- 포함 여부 관련 배열 메소드 : indexOf / lastIndexOf

let brands = ['Google', 'Kakao', 'Naver', 'Kakao'];

console.log(메소드('KaKao');
console.log(메소드('Daum');
메소드 역할 콘솔 결과
indexOf(item,startIndex) startIndex부터의 요소 중 item이 있는지 앞에서부터 확인하여 index 반환
item = 필수 / startIndex = 선택(없으면 맨 앞부터 확인)
1
-1
lastIndexOf(item, endIndex) endIndex부터의 요소 중 item이 있는지 뒤에서부터 확인하여 index 반환
item = 필수 / endIndex = 선택(없으면 맨 뒤부터 확인)
3
-1
includes(item) 단순 포함 여부만 확인 true
false

* 포함되어 있지 않다면, -1이 리턴됩니다.
** 여러 번 포함되어 있으면, 처음 발견된 인덱스가 리턴됩니다.

 

- 자주 쓰이는 배열 메소드 (단순 요소 추가/제거, 순서변경)

let body = ['chest', 'arm', 'leg'];
메소드 역할 콘솔 결과
shift() 배열의 맨 앞 요소를 지움 [arm, leg]
pop() 배열의 맨 끝 요소를 지움 [chest, arm]
unshift(item) 배열의 맨 앞에 요소를 추가 [item, chest, arm, leg]
push(item) 배열의 맨 뒤에 요소를 추가 [chest, arm, leg, item]
reverse() 배열의 순서를 뒤집기 [leg, arm, chest]

 

 

 

 

 

와 얼마만의 복습이지...

나머지는 어느정도 알고 있다 생각해서 안했는데(그래서 객체까지는 어케 넘김) 배열 메소드는 난리다...

머리에 푹푹 넣어보자

반응형