본문 바로가기
카테고리 없음

자바스크립트 for-of 문법

by nh_3521099031483 2024. 3. 27.
let initialCurrentWeatherData = res.data.response.body.items;
                let T1H = initialCurrentWeatherData.item.find(temp => temp.category === 'T1H').obsrValue // 기온 데이터
                let RN1 = initialCurrentWeatherData.item.find(temp => temp.category === 'RN1').obsrValue
                // let REH = initialCurrentWeatherData.item.find(temp => temp.category === 'REH').obsrValue
                // let PTY = initialCurrentWeatherData.item.find(temp => temp.category === 'PTY').obsrValue
                let WSD = initialCurrentWeatherData.item.find(temp => temp.category === 'WSD').obsrValue

                if (T1H > 30) feeling.value = "매우 더움";
                if (T1H <= 30) feeling.value = "더움";
                if (T1H <= 25) feeling.value = "보통";
                if (T1H <= 20) feeling.value = "선선함";
                if (T1H <= 15) feeling.value = "쌀쌀함";
                if (T1H <= 10) feeling.value = "추움";
                if (T1H <= 0) feeling.value = "매우 추움";

위와 같은 코드를 for-of 문법으로 표현할 것이다

const tempPoints = [0, 10, 15, 20, 25, 30];
                for (const num of tempPoints) { // 한 번의 반복이 실행될 때마다 어떤 요소를 반복을 돌렸는지 각각을 num으로 받는다
                    console.log(num);
                    console.log(typeof num);
                }

배열안의 타입이 number니까 당연히 타입도 number로 찍힌다.

 

const obj = {name1: "", name2: "", name3: "",}
                for (const item in obj) { // 객체를 반복문 돌릴때는 for-of가 아니라 for-in을 사용한다
                    console.log(item)
                    console.log(typeof item)
                }

key값만 찍히는 것을 확인해 볼 수 있다.

 

객체는 배열과 다르게 활용범위가 다를 수 있기 때문에 for-in문법을 통해 key-value 값을 뽑아낼 때는 데이터 재가공이 필요해보인다.

 

잘 정리되어 있는 자료가 있어서 가져와 봤다

                const tempPoints = [0, 10, 15, 20, 25, 30];
                const lavels =["매우 추움", "추움", "쌀쌀함", "선선함", "보통", "더움", "매우 더움"];

                let index = 0; // 인덱스를 0으로 세팅
                for (const point of tempPoints) { // for-of문법을 활용해서 반복된 요소 하나하나의 이름을 point라고 지정
                    if (T1H <= point) break; // 만약 현재 온도 데이터 값이 우리가 지정해준 point값보다 작으면 break를 걸고
                    index++; // index값을 증가
                }
                // 그 온도에 대한 알맞은 lavel값을 feeling이라는 데이터에 할당시켜준다
                feeling.value = lavels[index] // feeling역시 ref라는 메서드를 참조해서 만든 데이터이기 때문에 value로 접근, 데이터 할당 후 lavel의 index값을 넣어준다