0

The first time the loop runs, there's no problem. The get's shown when the loop ends, and every other time the loop runs. The .checked property works fine, to my knowledge, there's just the error... Does someone know what to do about this? My background in javascript isn't that broad, and I'm still learning. Thanks you.

I have already tried .checked === true and .checked == checked ...

In the code snippet below dishes is an array of radiobuttons.

    for (i = 0; i <= dishes.length; i++) {
       if (dishes[i].checked) {
         switch (dishesClass) {
        .........
         }
       }
     }

I expect no error in the console, but there are multiple. Every time the loop ends, the console states the same error.

Uncaught TypeError: Cannot read property 'checked' of undefined

4
  • Can you show the code for adding values to dishes array Commented Jun 1, 2019 at 13:45
  • I swear that Cannot read property x of undefined is the most asked question on SO 😂 Show us the current state of dishes please. Commented Jun 1, 2019 at 13:45
  • 2
    Ah, just remove the < from <= Commented Jun 1, 2019 at 13:45
  • i <= dishes.length -> i < dishes.length Last element in the array is dishes[dishes.length - 1]. Commented Jun 1, 2019 at 13:46

2 Answers 2

1

In your for loop you are testing if i is less than or equal to dishes.lengh. You just need to check if it is less than, since i starts from 0, as does array indexes in computing.

So just replace i <= dishes.length; with i < dishes.length;

Hope that helps

This code will work

for (i = 0; i < dishes.length; i++) {
   if (dishes[i].checked) {
     switch (dishesClass) {
    .........
     }
   }
 }

This resource, on Loops and Iteration may help you.

Sign up to request clarification or add additional context in comments.

Comments

0

As pointed by @Alicia, the problem is in your loop condition i<= whereas it should be i<. The array index i tries to access an element outside of the array bounds on the last iteration. Array's index starts at zero and ends at the array length - 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.