Take the 2-minute tour ×

Is it possible to set the custom index of an array with a variable.

for example:

var indexID = 5;
var temp = {
    indexID: new Array()

The above example sets the array index to indexID and not 5. I have tried using = snd quotes but I without any success.


share|improve this question
Just for clearity. temp is not an array. –  Bart May 20 '13 at 9:50
This is still not working. This works: var temp = {5:new Array()}; - but if I substitute the 5 for a variable it falls over. I have tried all suggested solutions... –  Alan A May 20 '13 at 10:04
Ok yes I see I am confusing arrays and objects. Put another way, what I am trying to do is create an array which has as it's first numeric index a value other than 0. So the first index in my case would be 5. –  Alan A May 20 '13 at 10:13
add comment

4 Answers

up vote 1 down vote accepted

Yes, just use square brackets notation:

var temp = {};
temp[indexID] = [];

Also pay attention to the fact that temp is an object, and not an array. In JavaScript all associative arrays (or dictionaries) are represented as objects.

MORE: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId

share|improve this answer
Thanks for the helpful answers. I think what I was trying to do was not best practice so I have changed my approach and used 0 as the first index of the array. I was trying to double the index of the array as variable which in hindsight isn't practical. –  Alan A May 20 '13 at 10:26
add comment

I think what you want is:

var indexID = 5;
var temp = {};
temp[indexID] = "stuff"
share|improve this answer
add comment

With your code, you will create an object.

Instead you can do

var indexID = 5;
var temp = [];
temp[indexID] = [];
share|improve this answer
add comment

You are mixing Array with Object. Arrays know a (numeric) index, Objects consist of key-value pairs, where key may be any string.

Not everyone would agree, bu you could extend Object.prototype

Object.prototype.append = function(key,val){
  // confine to Object instances
  if (this.constructor !== Object && 
      !/object/i.test(this.constructor.prototype)) { return this; }
  this[key] = val;
  return this;

And subsequently use:

var temp = {}.append(indexID,[]};
share|improve this answer
add comment

Your Answer


