프론트엔드 스쿨 5기 TIL - 4월 6일 - 반복문 (1) - for..in & for..of

크롱·2023년 4월 7일
0

JavaSrcipt

목록 보기
14/53

🌈 반복문

<script>
  for (let i = 0; i < 10; i++) {
      console.log(i) // 0부터 9까지 출력
  }
  // console.log(i) // i는 반복문이 끝난 다음 호출할 수 없습니다.
  
  for (let i = 0; i < 10; i++) {
    console.log(10);
  } // 10 이 10번 출력됩니다.
</script>

🌃 무한 루프 예시

Math.floor(Math.random() * 5)
0부터 4까지 랜덤하게 반환합니다.

<script>
  let answer = Math.floor(Math.random() * 100)
  // ~~(Math.random()*100) // 0부터 99까지 랜덤하게 반환
  let count = 0

  for (; ;) {
      count += 1 
      //만약 맞춘다면 0번째 맞췄습니다 보다 1번째 맞췄다는게 더 나으니 일단 1을 추가하고 시작
      
      let userInput = parseInt(window.prompt('값을 입력해주세요!'))
      
      if (answer > userInput) {
          window.alert('UP!')
      }
      else if (answer < userInput) {
          window.alert('DOWN!')
      }
      else if (Number.isNaN(userInput)) {
          window.alert('다시 입력하세요!')
          //만약 문자열을 입력하면 userInput은 parseInt('문자열'), 즉 NaN 이된다.
      }
      else {
          window.alert('Correct!')
          break // for 문 자체를 빠져나온다.
      }
  }

  console.log(`${count}번째 맞추셨습니다!`)
</script>


🌞 반복문 for..in 과 for..of

for in와 for of문에서는 const가 가능

🌃 for..in

  • for..in 반복문은 배열이 아니라 객체와 함께 사용할 때 최적화되어 있어서 배열에 사용하면 객체에 사용하는 것 대비 10~100배 정도 느립니다.
  • 배열 array엔 되도록 for..in를 쓰지 마세요. 배열의 순회는 map, forEach를 더 권장
  • for..in 반복문은 모든 프로퍼티를 대상으로 순회합니다. 키가 숫자가 아닌 프로퍼티도 순회 대상에 포함됩니다.
<script>
// 예제 1
  for (const i in 'hello world') {
      console.log(i) // index를 반환하므로 문자열로'0'부터 '10'까지 반환
  }

// 예제 2
  let s = 0
  for (const i in '.'.repeat(101)) {
      s += parseInt(i)
  }
  console.log(s) //5050

// 풀이 
// '.'.repeat(101) => .이 101개가 생성
// for..in 문이므로 i는 index, 0부터 100까지 순회합니다. 
//이때 i는 문자열이기땜시 parseInt를 해주는 거에용.
//0부터 100까지더하는거죵.


----------------------------------------------

  let arr1 = [10, 20, 30, 40, 50]
  let obj1 = { 'one': 10, 'two': 20 }
  // array에서 for in문을 쓰지 않기를 권해드립니다.

  for (const i in arr1) {
      console.log(arr1[i]) // i는 index이므로 10,20,30,40,50반환
  }

  for (const i in obj1) {
      console.log(obj1[i]) // i는 key // 10,20 반환
  }

</script>


🌃 for..of

<script>
  let arr2 = [10, 20, 30, 40, 50]
  let obj2 = { 'one': 10, 'two': 20 }

  for (const item of arr2) {
      console.log(item) // 10,20,30,40,50 반환
  }

  let s = 0
  for (const item of arr2) {
      s += item
  }
  console.log(s) // 150

  // for (const item of obj2) { // of 뒤에 iterable한 값이 나와야 합니다.
  //     console.log(item) //에러
  // }

  for (const item of 'hello world') {
      console.log(item) // 'h' 'e' .....'d'
  }
  
  
  -----------------------------------
  //배열에서 for in 과 for of 
  
    for (const i in [1, 2, 3]) {
      console.log(i)
  } //'0','1','2' 출력 ! for..in은 인덱스 출력

  for (const i of [1, 2, 3]) {
      console.log(i)
  } // 1,2,3 출력
</script>

📌 연습문제

다음 수학 점수의 반평균을 구하세요.
let 수학점수 = [10, 99, 89, 70]

<script>
  let 수학점수 = [10, 30, 80, 40]

  let sum = 0;
  for(const i of 수학점수) {
    sum += i;
  }
  console.log( sum / 수학점수.length) //40
</script>

다음 user의 나이 평균을 구하세요.
let user = [
{
"_id": "642e3071c61a23c70ae6076b",
"index": 0,
"age": 31,
"name": "Hicks Garza",
"gender": "male",
},
{
"_id": "642e3071ecd6f90a87d64731",
"index": 1,
"age": 32,
"name": "Ayers Harrington",
"gender": "male",
},
{
"_id": "642e3071cef9ddc131f047fb",
"index": 2,
"age": 39,
"name": "Lamb Adams",
"gender": "male",
}
]

<script>

  let sum = 0
  for(const i in user){
    sum += user[i]['age']
  }
  console.log(sum/user.length)
  
</script>
  • 만약 한명이 age가 없다면?
<script>
let user = [
    {
        "_id": "642e3071c61a23c70ae6076b",
        "index": 0,
        "age": 10,
        "name": "Hicks Garza",
        "gender": "male",
    },
    {
        "_id": "642e3071ecd6f90a87d64731",
        "index": 1,
        "age": 40,
        "name": "Ayers Harrington",
        "gender": "male",
    },
    {
        "_id": "642e3071cef9ddc131f047fb",
        "index": 2,
        "age": 30,
        "name": "Lamb Adams",
        "gender": "male",
    },
    {
        "_id": "642e3071cef9ddc131f047fb",
        "index": 2,
        "name": "Lamb Adams",
        "gender": "male",
    }
]

let s = 0
for (const i of user) {
    console.log(i) // 요소{}를 하나씩 반환
    console.log(i.age) // 마지막에 undefined
    console.log(s) 
    console.log('----------')
    s += i.age ?? 0 
  // age가 없는 프로퍼티는 undefined를 반환하므로 0을 대신 더해줍니다. 
  // 만약 undefined를 더해주면 NaN이 되어 평균을 구할수없어요!
}
console.log((s / user.length).toFixed(2))




// 또다른 코드로 풀이해보자
let s = 0          // user.map(v => v.age) 는 [10,40,30,undefined]
for (const i of user.map(v => v.age)) {
    if (!!i) {
        s += i
    }
}
console.log((s / user.length).toFixed(2)) 

//참고
!!31 // true
!!1 // true
!!-1 // true
!!0 // false

</script>

📘 외우세호

<script>
!true   	// false
!false 	 	// true
!!31   		// true
!!1   	 	// true
!!-1  	 	// true
!!0    		// false
!!'hello'   // true
!!NaN       // false
!!undefined // false
!!null      // false

///// 외우세요. /////
user
    .map(v => v.age) //  [10,40,30, undefined]
    .filter(v => !!v) 
    //  [10,40,30, undefined] 이 배열 요소 중 값이 잇는것만 반환하라! 
    //즉,undefined, null, NaN을 제거해줍니다. [10,40,30]
    .reduce((a, b) => a + b, 0) // 배열 요소 다 더해!
</script>
profile
👩‍💻안녕하세요🌞

0개의 댓글