본문 바로가기

COA Lab's JS

자바스크립트 22 - for 정리

자바스크립트에서는 여러가지 형태의 for문이 있다. 

 1. 일반적 for문  : 일반적으로 가장 많이 사용한는 for문의 형태

for(let i=0; i<5;i++){..}

2. 객체순환하는 for in문

for(let key in obj){

      console.log(key, obj[key);

}

3. 배열값을 순환하는 for of문 : es6에서 새롭게 들어온 문법

for(let value of arrList){

      console.log(value);

}

4. 배열객체에서만 가능한 forEach문 : es6에서는 map, set을 지원한다.

Array.forEach(function(item, idex, arr){

      //배열의 값, 순서, 배열 자체를 순환한다. 

};)

 

[tip]  for in과 for of의 차이점 

- for in은 객체의 모든 속성을 반복한다.

- for of는 배열의 값을 반복한다. 

 

ref ] 

www.w3schools.com/js/js_loop_for.asp

 

JavaScript for Loop

JavaScript For Loop Loops can execute a block of code a number of times. JavaScript Loops Loops are handy, if you want to run the same code over and over again, each time with a different value. Often this is the case when working with arrays: Instead of w

www.w3schools.com

www.w3schools.com/js/js_loop_forin.asp

 

JavaScript For In

JavaScript For In The For/In Loop The JavaScript for/in statement loops through the properties of an Object: Syntax for (key in object) {   // code block to be executed } Example var person = {fname:"John", lname:"Doe", age:25}; var text = ""; var x; for

www.w3schools.com

 

www.w3schools.com/js/js_loop_forof.asp

 

JavaScript For Of

JavaScript For Of The For/Of Loop The JavaScript for/of statement loops through the values of an iterable object. It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more: Syntax for (variable of iterable) {   // c

www.w3schools.com

 

www.w3schools.com/jsref/jsref_foreach.asp

 

JavaScript Array forEach() Method

JavaScript Array forEach() Method Example List each item in the array: var fruits = ["apple", "orange", "cherry"]; fruits.forEach(myFunction); function myFunction(item, index) {   document.getElementById("demo").innerHTML += index + ":" + item + "
"; }

www.w3schools.com