๋ฐ๋ณต๋ฌธ for์ ๊ณ ์ฐจํจ์๋ผ๊ณ ๋ณด๋ฉด ๋๋ค. ๊ฐ๋ฐ์ ํ๋ค๋ณด๋ฉด for๋ฌธ๊ณผ if ํจ์๋ฅผ ํจ๊ป ์์ฃผ ์ฌ์ฉํ๊ณ ์๋๋ฐ, ์ด๋ฌํ ๋ฐฉ๋ฒ์ ์กฐ๊ฑด๋ฌธ์ด๋ ๋ฐ๋ณต๋ฌธ์ ๋ก์ง์ ์ฝ๊ฒ ์ฝํ์ง ์์ ๋๊ฐ ์๋ค.
์ด๋ฅผ ๋ณด์ํ๊ธฐ ์ํด์ ํ์ํ ๊ฒ์ forEach!
forEach ๋ฉ์๋๋ ์์ ์ ๋ด๋ถ์์ ๋ฐ๋ณตํ๋ฉฐ ์์ ์ ๋ถ๋ฌ๋ธ ๋ฐฐ์ด์ ์์์ ์ํํด์ค๋ค!
์ฆ, ๋ ๊ฐํธํ๊ฒ ๋ฐ๋ณต๋ฌธ์ ์คํํ ์ ์๋ค๋ ์๊ฐ์ด ๋ค์๋ค.
์๋๋ ๊ฐ์ ๊ฒฐ๊ณผ๊ฐ์ ๊ฐ๊ฐ for๊ณผ forEach๋ก ํํํ ๊ฒ์ด๋ค.
const arr = [10,20,30]
const num = [];
//for ๊ตฌ๋ฌธ
for(i=0; i<arr.length; i++){
num.push(arr[i]*2);
}
console.log(num); //[20,40,60]
//forEach ๊ตฌ๋ฌธ
arr.forEach(e => num.push(e*2))
console.log(num);//[20,40,60]
forEach๋ ์ฝ๋ฐฑํจ์๋ก ์ ๋ฌ๋ฐ์ ๋ฐ๋ณต ํธ์ถํ๋ ๋ฐฉ์์ธ๋ฐ,
์์์ ๋ฐฐ์ด์ ์์๊ฐ 3๊ฐ๋ผ์ 3๋ฒ์ ์ฝ๋ฐฑํจ์๋ฅผ ๋ถ๋ฌ์จ๋ค.
const num = [1,2,3]
//arrow Function ํํ
num.forEach((item,index,arr) => {arr[index] = item ** 2;};)
console.log(num);// [1,4,9]
//์ผ๋ฐ fucntion
num.forEach(funciotn(item,index,arr){
arr[index] = item ** 2;
})
console.log(num);// [1,4,9]
1) item: forEach๋ฅผ ํธ์ถํ ๋ฐฐ์ด์ ์์๊ฐ
2) index: forEach๋ฅผ ํธ์ถํ ๋ฐฐ์ด์ ์ธ๋ฑ์ค
3) arr: forEach๋ฅผ ํธ์ถํ ๋ฐฐ์ด
๋ฌธ์ 1 ) p ํ๊ทธ๋ฅผ ๋๋ฅด๋ฉด ๋ฌธ๊ตฌ์ํจ๊ป ๊ฒฝ๊ณ ์ฐฝ์ ๋์๋ผ
๊ธฐ๋ณธ for ๊ตฌ๋ฌธ ํ์ด
<p>1. ์ค๋ ์ ๋
์๋ ๋ถ๋์ฐ๊ฒ๋ฅผ ๋์ฌ ๋จน๊ฒ ๋ค.<button type="button">์ญ์ </button></p>
<p>2. ํ์์ผ๋ก ์ํ
์คํ๋ฅผ ๋จน๊ฒ ๋ค.<button type="button">์ญ์ </button></p>
<p>3. ์๊ธฐ ์ ์ ๋ฐ๋์ ๋ด์ผ ์์นจ ๋ฉ๋ด๋ฅผ ์๊ฐํด๋๊ฒ ๋ค.<button type="button">์ญ์ </button></p>
<script>
const txts = document.querySelectorAll('p');
for(let i = 0; i <txts.length; i++){
txts[i].addEventListener('click',(event) => {
alert(event.target.textContent.slice(0,-2));
})
}
</script>
forEach๋ฌธ์ ๋ฌธ์
mdn ๋ฌธ์๋ฅผ ๋ณด๋ฉด Array.prototype.forEach๋ผ๊ณ ์ ํ์๋ค. ๊ทธ๋ฌ๋ forEach๋ nodelist๋ HTMLcollection์ ๋ชจ๋ ์ฌ์ฉํ ์ ์๋ค. ์ด๋ฐ forEach๊ฐ ie ์ง์์ ํธํ๋ฌธ์ ๊ฐ ์๋ค. ๋ฌผ๋ก ๋ฐ๋ฒจ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ฑ์ ์ด์ฉํ๋ฉด ์ฝ๊ฒ ํธํํ๋ ๋ฐฉ๋ฒ๋ ์์ง๋ง, Array.prototype.forEach.call
๋ฅผ ์ฌ์ฉํด์ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์๋ ์๋ค.
const txts = document.querySelectorAll('p');
Array.prototype.forEach.call(txts,(item) => {
item.addEventListener('click',(event) => {
alert(event.target.textContent.slice(0,-2));
})
์ด ๋ฐฉ๋ฒ์ txts์ ์๋ forEach๊ฐ ์๋ ๊ฒ์ฒ๋ผ ํด์ค๋ค. ํ๋กํ ํ์ ์ ๋ฉ์๋์ ์ ์ฅ๊ณต๊ฐ์ผ๋ก ๋ณด๋ฉด๋๋๋ฐ, ๊ฐ์ฒด์ ์ฐ๊ฒฐํด์ฃผ๋ ์ญํ ์ ํ๋ค.
๋ฌธ์ 2 ) ๋ฒํผ์ ๋๋ฅด๋ฉด ์ปดํ ์ฐฝ์ด ๋จ๊ณ , ํ์ธ์ธ์ ๋๋ฅด๋ฉด p ํ๊ทธ๋ฅผ ์ญ์ ํด๋ผ
for (const item of btns) {
item.addEventListener('click',(event) => {
let result = confirm('์ญ์ ํ ๋?');
// ์ด๊ฑฐ ์ํด์ฃผ๋ฉด ๋ฒ๋ธ๋งํ๋ฉด์ ์์ p์ alert๋ฅผ ์คํ
event.stopPropagation();
if(result){
item.parentElement.remove();
}
})
}
txts.remove()๋ฅผ ํ๋ฉด ์๋๋ ์ด์ ๋ txts๋ ๋
ธ๋๋ฆฌ์คํธ๋ผ์ ์ฌ๋ฌ ๋
ธ๋๋ค์ ๋ค ์ง๋ชฉํ๊ณ ์์!
๊ทธ๋์ ์ ํํ ๋ฒํผ์ธ์ง p์ธ์ง ๊ฐ๋ฅดํค๋ ๋์์ ์ ์ ์์ด์ parentElement๋ก ์ ํํ๊ฒ ์ง์ด์ค์ผ ํจ.
confrim์ ํ์ธ ๋ฒํผ์ true, ์ทจ์๋ false๋ค.