i'm not really sure, how to explain this, but i trying to create a multidimensional anonymes array in javascript. I'm new to Javascript and mostly did jQuery stuff so far. But now i need this and what i am trying to achieve should work like this somehow:
var
outerArray = [],
innerArray = new Array("position", "value", "done");
outerArray.push(innerArray);
// Then i want to use
outerArray["dynamicNameHere"]["position"] = 30;
outerArray["dynamicNameHere"]["value"] = 50;
outerArray["dynamicNameHere"]["done"] = false;
outerArray["otherDynamicNameHere"]["position"] = 100;
outerArray["otherDynamicNameHere"]["value"] = 500;
outerArray["otherDynamicNameHere"]["done"] = true;
The array is two-dimensional. Some values are booleans, but most of them are just integers as you can see in my example code. I hope my code help you understand my intention, because i'm not sure, how to explain it further. And, i know this code above doesn't work, but i have no idea, how to create something like this or if this is even possible with javascript (in PHP it is at least). This was just some code snippets i found about arrays and hoped this could work. But it didn't. But to me "push" seems like the way to do this?
Thanks for your help and time.
2 Answers 2
Arrays in JavaScript are for numerical indices only. There are no associative arrays.
You seem to want plain, nested objects:
outerObject = new Object();
outerObject["dynamicNameHere"] = new Object();
outerObject["dynamicNameHere"]["position"] = 30;
outerObject["dynamicNameHere"]["value"] = 50;
outerObject["dynamicNameHere"]["done"] = false;
outerObject["otherDynamicNameHere"] = new Object();
outerObject["otherDynamicNameHere"]["position"] = 100;
outerObject["otherDynamicNameHere"]["value"] = 500;
outerObject["otherDynamicNameHere"]["done"] = true;
But lots easier to use is the object literal notation:
var outerObject = {
dynamicNameHere: {
position: 30,
value: 50,
done: false
},
otherDynamicNameHere: {
position: 100,
value: 500,
done: true
}
}
Though, if those property names are really dynamic you will need to use the bracket notation for them:
var outerObject = {}, // empty object
dynamicName = ...,
otherDynamicName = ...;
outerObject[dynamicName] = {
position: 30,
value: 50,
done: false
};
outerObject[otherDynamicName] = {
position: 100,
value: 500,
done: true
};
4 Comments
outerObject?if( !(dynamicPropName in outerObject)) { /* doesn't exist */) which is a bit more reliable than checking for undefined.It seems more, that you need an object and not an array:
var outerArray = {};
// add elements
outerArray[ 'dynamicNameHere' ] = {
'position': 30,
'value': 50,
'done': false
};
// access those
console.log( outerArray[ 'dynamicNameHere' ][ 'position' ] );
// or
console.log( outerArray[ 'dynamicNameHere' ].position );
Comments
Explore related questions
See similar questions with these tags.