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
6 Answers 6
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
1 Comment
I think what you want is:
var indexID = 5;
var temp = {};
temp[indexID] = "stuff"
Comments
With your code, you will create an object.
Instead you can do
var indexID = 5;
var temp = [];
temp[indexID] = [];
Comments
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
for node-red project i had to add Apostrophe to the index name
var Trend_1={};
Trend_1[**'x'**]=Date_TimeArray;
Comments
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"
tempis not an array.