Javascript [ 배열 For 문 ]

양혜정·2024년 4월 7일
0

javascript_web

목록 보기
15/81

For문 종류

첫번째 ( For )

let html = `<ol>`;
for(let i=0; i<배열명.length; i+=1){
	html += `<li>${배열명[i]}</li>`;
}	// end of for--------
html += `</ol>`;

두번째 ( For ~ of / For ~ in )

  • For of => 배열값을 가져올 때 사용
let html = `<ol>`;
for(let item of 배열명){
	html += `<li>${item}</li>`;
}	// end of for-------
html += `</ol>`;
  • For in => 객체의 속성목록을 가져올 때 사용
for(let property_name in 배열명){
	console.log(배열명[property_name]);
  	// property_name 은 속성명 변수로 임의 지정(다른이름 가능)
  	// 속성명은 . 표기법이 아니라 반드시 대괄호 표기법 사용 !!
}	// end of for---------------
  • For of 와 For in 혼합 사용
let html = ``;
for(let item of 배열명){
	html += `<div><ul>`;
  	for(let property_name in item){
    	html += `<li>${item[property_name]}</li>`;
    }	// end of for--------
  	html += `</ul></div>`;
}	// end of for------------

세번째 ( ForEach )

let html = `<ol>`;
배열명.forEach(function(item, index, array){
	html += `<li>${item}</li>`;
  	html += `<li>${array[index]}</li>`;
})
html += `</ol>`;

// === ForEach 화살표 함수(1) === //
let html1 = `<ol>`;
배열명.forEach((item) =>{	
  	// function 생략
  	// 사용하지 않는 파라미터 생략, item 은 생략 불가능
	html1 += `<li>${item}</li>`;
})
html1 += `</ol>`;

// === ForEach 화살표 함수(2) === //
let html2 = `<ol>`;
배열명.forEach(item => {
  	// 파라미터가 하나일 경우 () 생략
  	// function, 사용하지 않는 파라미터 생략
	html2 += `<li>${item}</li>`;
})
html2 += `</ol>`;

// === ForEach 화살표 함수(3) === //
let html3 = `<ol>`;
배열명.forEach(item => html2 += `<li>${item}</li>`)
  	// 처리해야할 내용이 1개 밖에 없으면 {} 와 ; 생략
  	// function, 사용하지 않는 파라미터 생략
	// 파라미터가 하나일 경우 () 생략
html3 += `</ol>`;

정리

  • 09_javascriptStandardObject
    -> 01_Array_class -> 01_forOf_forEach_push_pop_splice_reverse_sort_slice_indexOf.html, 01.css, 01.js

0개의 댓글

관련 채용 정보