본문 바로가기

블록체인 sw개발자

[JS] for 문

for 문은 while 문과는 달리 자체적으로 초기식, 표현식,증강식을 모두 포함하고 있는 반복문이다.

따라서 while 문보다는 좀 더 간결하게 반복문을 표현 할 수 있다.

 

for

for (초기식; 조건식; 증감식) {
  조건식의 결과가 참인 동안 반복적으로 실행하고자 하는 실행문;
}

for 문을 구성하는 초기식, 조건식, 증감식은 각각 생략될 수 있다.

또한, 쉼표 연산자(,) 를 사용하면 여러 개의 초기식이나 증감식을 동시에 사용할 수도 있습니다.

for 문을 사용하면 앞선 예제의 while 문을 더욱 더 간결하게 표현할 수 있다.

 

for in 

객체의 프로퍼티 키 열거 전용

=> for(const key in 객체) {..반복수행 코드}

const obj = {
   name: 'curryyou',
   job: 'engineer'
   }
   
for (const key in obj{
   console.log('${key} : ${obj[key]);
 }

*(주의) 해당 객체가 상속받는 프로토타입 체인상의 모든 프로포티 키를 열거한다.

 

for of 문

이터러블 순회 전용

=>for(const item of 이터러블) {..반복 수행 코드..}

const arr = [10, 20, 30];
for (const item of arr){
   console.log(item); //10 20 30출력

*(참고) 이터러블에는 String, Array, Map, Set, DOM컬렉션(HTMLCollection,Nodelist)등이 있다.

 

 

함수와 value

 

ex) 학생 명단을 추가 및 클릭제거한다. 함수를 바깥으로 뺴놓고 function을 이용한다

 

html

 

 

[JS]

const stydentList = document.getElementByid("students");
function addStudentFunc(value) {
   const tempElem = document.createElement("li");
   tempElem.innerHTML = value;
   tempElem.onclick = function () {
   // addStudentFunc(value);
   tempElem.outerHTML = "";
 };
 studentList.append(tempElem);
 }
 
 const students = ["사과", "바나나", "딸기"];
 //studentList[0] = "체리"
 for (let i = 0; i < students.length; i++) {
    addStudentFunc(students[i]);
 }
 
 const button = document.getElementById("add-student");
 const addStudent = document.getElementById("name");
 button.onclick = function () {
 addStudentFunc(addStudent.value);
 };

 

'블록체인 sw개발자' 카테고리의 다른 글

[JS] object(객체)  (0) 2023.07.06
[JS] scope  (0) 2023.07.05
[JS] 함수  (0) 2023.06.30
[JS] while, 구구단 만들기  (0) 2023.06.29
[JS] 배열함수  (0) 2023.06.28