배열 조작
추가하기
- 배열.push('요소') = 배열 뒷 부분에 요소 추가
const classmate = ['chu', 'choi', 'park', 'Lee']
classmate.push('royud')
console.log(classmate) // ['chu', 'choi', 'park', 'Lee', 'royud']
const classmate = ['chu', 'choi', 'park', 'Lee']
classmate[5] = 'royud'
console.log(classmate) // ['chu', 'choi', 'park', 'Lee', empty, 'royud'] -> empty = 비어있다는 뜻
수정하기
- 배열.splice('인덱스', '제거할 요소의 갯수', '요소') = 해당 인덱스부터 갯수만큼 지우고 요소를 추가
const classmate = ['chu', 'choi', 'park', 'Lee', 'Lee2']
classmate.splice(4, 1, 'royud') // ['Lee2'] -> 잘라낸 부분을 리턴
console.log(classmate) // ['chu', 'choi', 'park', 'Lee', 'royud']
//갯수를 0으로 하여 추가만 하기 가능
const classmate = ['chu', 'choi', 'park', 'Lee']
classmate.splice(classmate.length, 0, 'royud') // []
console.log(classmate) // ['chu', 'choi', 'park', 'Lee', 'royud']
// 요소를 작성하지않으면 제거만 하고 리턴
const classmate = ['chu', 'choi', 'park', 'Lee', 'royud', undefined]
classmate.splice(5, 1) // [undefined]
console.log(classmate) // ['chu', 'choi', 'park', 'Lee', 'royud']
//응용 -> indexOf()를 이용하여 원하는 요소의 인덱스를 찾아 수정
const classmate = ['chu', 'choi', 'park', 'Lee', 'Lee2']
const mate = classmate.indexOf('Lee2')
classmate.splice(mate, 1, 'royud')
console.log(classmate) // ['chu', 'choi', 'park', 'Lee', 'royud']
잘 안쓰던 반복문
for in
const classmate = ['chu', 'choi', 'park', 'Lee', 'royud']
for(const i in classmate){
console.log(`우리 ${classmate[i]}님 화이팅!`)
}
//
우리 chu님 화이팅!
우리 choi님 화이팅!
우리 park님 화이팅!
우리 Lee님 화이팅!
우리 royud님 화이팅!
for of
const classmate = ['chu', 'choi', 'park', 'Lee', 'royud']
for(const mate of classmate){
console.log(`우리 ${mate}님 화이팅!`)
}
//
우리 chu님 화이팅!
우리 choi님 화이팅!
우리 park님 화이팅!
우리 Lee님 화이팅!
우리 royud님 화이팅!
while
// 조건에 큰 비중이 있을 때 사용하는 것이 좋음
let i = 0
while(confirm('빵 안사와도 괜찮아ㅎㅎ')){
i++
alert(`${i}번 얘기했다. 다시 말할게~`)
}
alert('그래 다녀와 ~')
//
확인 버튼 눌릴 때까지 반복문 반복
취소를 누르면 alert 출력