2

I want to use a variable as the index parameter in an array but for some reason it's coming up as "undefined" when I do it this way. Any ideas?

var object_number = [];
var x = 1;

    function create_new_object()
    {
        object_number[x] = new happy_object();
        x++;

    }
3
  • Did you actually call create_new_object()? Commented Mar 23, 2011 at 17:52
  • are you accessing object_number[0] ? because you are setting x=1 so index 0 will be undefined if you are trying to access it. Commented Mar 23, 2011 at 17:54
  • 1
    Do you actually define happy_object? (Seriously, this reduced test case has been reduced too far to possibly work, it doesn't even have a line of code that could have anything come up as 'undefined') Commented Mar 23, 2011 at 17:55

4 Answers 4

3

Array indices start at zero in JavaScript. When x starts at 1, there's an undefined element in the first position of the array. Start at x=0 instead.

There's a better way to do this, however. Instead of manually keeping track of the last element in the list, you can just use Array.push() to add a new element onto the end.

var object_number = [];

function create_new_object()
{
    object_number.push(new happy_object());
}

When you want to find out how many elements are in the array, use Array.length (or the number returned by Array.push()).

Further reference: Array @ MDC.

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

Comments

1

your object_number is an empty array with no elements. Hence you are getting this error. To add elements to array, you need to use push method.

object_number.push(new happy_object() );

Also you need to start your array index from 0 instead of 1. i.e. your x should be 0.

Comments

0

In addition to the previous answers:

Unlike "normal" languages (which use block-scope), javascript uses function-scope. So be shure x exists in side your function-scope when you use it like that.

Comments

0

you can't mess with array keys too too much in js - if you want a more solid, definable relationship, you'll need to mimic an associative array by doing:

var object_number = {};
var x = 1;

function create_new_object() {
    object_number[x] = new happy_object();
}

Also, I'd combine your var statements. Makes variable/function hoisting a bit clearer.

var object_number = {}
  , x = 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.