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++;
}
4 Answers 4
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.
Comments
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
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
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;
create_new_object()?object_number[0]? because you are settingx=1so index 0 will be undefined if you are trying to access it.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')