"Uncaught Typeerror: number[i] is Undefined"

Asked

Viewed 14 times

-1

I am creating a calculator and on my console I only get the error:

Uncaught TypeError: number[i] is undefined. 

The code returns the expected working, but this error persists.

Follows the code:

let number = document.getElementsByClassName('number')

let calAction = function(){ 
    console.log('work')
}


function getNumberLoad(number){
    for(let i = 0; i <= number.length; i++)
        number[i].addEventListener('click', calAction, false)        
}

document.addEventListener('DOMContentLoaded', getNumberLoad(number), false)

  • Pq to TAG brasil?

  • The number of loops in the for is wrong when using <= you have defined one item more than the limit of found elements, the count is from 0, so the length has to be less and not less-or-equal. Should be for(let i = 0; i < number.length; i++)

1 answer

1


number.length will return the length of the array number. However, since arrays indexes in javascript (and in most programming languages) start with 0 (zero), the last index of the array is equal to its length minus 1. Therefore, the output condition of your for should be i < number.length.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.