0

[![enter image description here][1]][1]I have been struggling with F--king arrays and objects and they will not display to browser.

I have used a constructor to build the array and then pushed it to the array inventory. I've been fiddling with this for days and I just don't get it. This keeps stopping me in all my projects, the minute I try to access an array I get undefined All I've ever gotten is Undefined. I really don't understand what i've done wrong.

3
  • 2
    Welcome to SO. I would recommend checking out minimal reproducible example to learn more about how to minimize the code posted to best assist in receiving assistance. Commented Dec 16, 2022 at 22:23
  • In JavaScript, arrays are zero-indexed. That means your bounds-check should use i < length instead of i <= length. Commented Dec 16, 2022 at 22:35
  • Can you elaborate on your issue "getting undefined, undefined"? Maybe include an error log? Commented Dec 16, 2022 at 22:38

1 Answer 1

2

Your for loop says:

for (var i = 0; i <= inventory.length; i++)

But that will go past the last item in the array, because the last item in the array will have the index inventory.length-1 and not inventory.length.

Instead, do:

for (var i = 0; i < inventory.length; i++)
Sign up to request clarification or add additional context in comments.

10 Comments

I thought <= is equal too or less than ? however it doesnt fix my undefined undefined problem
@CTR it is. Which means if you have an array of 3 items, i will have the values 0,1,2,3 during the loop. But it should only have the values 0,1,2 during the loop.
@CTR please be specific about what buttons to press in your example in order to recreate the undefined problem
I have added an image to explain the problem I'm having
@CTR I don't see that when I load your code example, as long as the < change is made in the for loop. Do I need to push any buttons to see what you're seeing?
|

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.