Steve Smelty
Steve Smelty

Reputation: 25

Using a variable as an array parameter in javascript?

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++;

    }

Upvotes: 2

Views: 174

Answers (4)

Matt Ball
Matt Ball

Reputation: 359786

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.

Upvotes: 3

Sachin Shanbhag
Sachin Shanbhag

Reputation: 55489

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.

Upvotes: 1

Jess Jacobs
Jess Jacobs

Reputation: 1137

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;

Upvotes: 0

yoda2k
yoda2k

Reputation: 55

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.

Upvotes: 0

Related Questions