👀 조건이 참일때만 명령문을 실행, 거짓인 경우 다른 명령문 실행!
for(let i=i의 초기; i의 조건; i의 증감){실행코드}
//조건이 trun이면 한계값만큼 증가/감소하며 반복된다!
// 1씩 감소하는 배열 만들기
function a(start, end) {
var answer = [];
for(let i=start; i>=end; i--){
answer.push(i)
}
return answer;
}
console.log(a(10,3)); // [10,9,8,7,6,5,4,3]
while(조건문){실행코드}
// 조건문이 참이면 코드를 계속 실행한다!
// 조건이 참이면 무한 루프가 된다! 무한 루프는 피해야 한다!!
// n이 3보다 작으면 반복해 실행
// 매번 반복하면 n이 증가하고 x에 더해진다
// 첫번째 반복: n = 1, x= 1
// 두번째 반복: n = 2, x= 3
// 세번째 반복: n = 3, x= 6
// 종결
n=0;
x=0;
while(n<3){
n++;
x = x+n;
}
👀 object에 사용하면 편리하다!
// object 자료 갯수만큼 변수를 반복해준다!
for(let 변수 in object){실행코드}
const people = {name: 'su', fat: 'little bit', tall: 'small'}
fot(let key in people){
console.log(key) // name, fat, tall
console.log(people[key]) // su, little bit, small
}
👀 array에 사용하면 편리하다!
for(let 변수 of 이터러블){실행코드}
// 이터러블(iterable): 반복되는 배열, 컬렉션
const Eng = ["A", "B", "C", "D", "E", "F", "G"];
for(let alphabet of Eng ){
console.log(alphabet);
}
// A,B,C,D,E,F,G
for(let alphabet of Eng ){
if(alphabet == "D"){
break
}
else{
console.log(alphabet);
}
}
// A,B,C
for(let txt of "text to long" ){
console.log(txt);
}
// t,e,x,t, ,t,o, ,l,o,n,g
<span> 태그로 감싸기!<h2 class="stage"></h2>
let hcode= "" // 코드저장변수
let text = `for of문으로 텍스트감싸기`
for(let x of text ){
console.log(x); // text 글씨가 한글자씩 나온다!
if(x === " "){ // 만약 x의 글자가 공백이라면 띄어쓰기 해줘
x = " "
}
hcode += `<span>${x}</span>`; // x의 글자를 span 태그에 담아줘
}
document.querySelector(".stage").innerHTML = hcode; //h2 태그 안에 담아줘
👀 array에서만 사용할 수 있다!
array.forEach(function(ele,idx,obj){실행코드})
// ele : 배열값
// idx : 순번
// obj : 전체 배열
const dayOfWeek = ["mon" , "tue" , "wed" , "thu" , "fri" , "sat"];
dayOfWeek.forEach(function(ele,idx){
console.log('ele',ele); // 각각 "mon" "tue" ... "sat"
console.log('idx',idx); // 각각 0 1 2 3 4 5
console.log('obj',obj); // ['mon', 'tue', 'wed', 'thu', 'fri', 'sat']
});