12

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.

Thnaks

3
  • 1
    Just for clearity. temp is not an array. Commented May 20, 2013 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... Commented May 20, 2013 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. Commented May 20, 2013 at 10:13

6 Answers 6

22

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

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

1 Comment

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.
6

I think what you want is:

var indexID = 5;
var temp = {};
temp[indexID] = "stuff"

Comments

1

With your code, you will create an object.

Instead you can do

var indexID = 5;
var temp = [];
temp[indexID] = [];

Comments

0

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,[]};

Comments

0

for node-red project i had to add Apostrophe to the index name

var Trend_1={};

Trend_1[**'x'**]=Date_TimeArray;

Comments

0
var index=7;  //YOUR CUSTOM INDEX
var newarray=[];

If you need array index to be an array you can do it like this:

newarray[index] = {
                   'KEY':'VAL',
                   'KEY':'VAL',
                   'KEY':'VAL'
                    }

If you need to assign just a value to your custom array index you can do it like this:

newarray[index] = "ANY-THING-YOU-WANT"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.