알아볼 것
왜 for 루프는 작동하지 않고 forEach는 작동하는가?
파란배개
2020. 10. 12. 17:30
const targetName = document.querySelectorAll('.name');
for(let i = 0; i < targetName.length; i++) {
targetName[i].onClick = function() {
for(let j = 0; j < arr.length; j++) {
if(targetName[i].textContent === arr[j].firstName + ' ' + arr[j].lastName) {
return printRole(arr[j]);
}
}
}
}
//제대로 작동하지 않음
const targetName = document.querySelectorAll('.name');
targetName.forEach(function(el) {
el.addEventListener('click', function() {
for(let j = 0; j < arr.length; j++) {
if(el.textContent === arr[j].firstName + ' ' + arr[j].lastName) {
return printRole(arr[j]);
}
}
})
})
//제대로 작동함
관계가 있을 가능성이 있는 단서
document.querySelectorAll로 만들어진 NodeList는 유사배열이다.