With Node JS, is it possible to set multi dimensional arrays separately, using key strings like in PHP ?
myArray[5]['age'] = 38;
myArray[5]['name'] = 'Jack';
myArray[5]['location'] = 'Australia';
I think this is confusing in Node JS:
var myArray = {};
myArray['usedId'] = new Array('Jack', 38, 'Australia');
because I had to do:
console.log (myArray[5]["0"]);
and I'd rather prefer to have a better control using:
console.log (myArray[5]['name']);
Use an object, not an array:
myArray[5] = {
name: 'Jack',
age: 38,
location: 'Australia'
};
This will cause console.log (myArray[5]['name']);
to work perfectly.
Also, your myArray
is an object ({}
), not an array ([]
).
PHP arrays are weird and represent many data structures at once. An Array in JavaScript is closer to an traditional array although it is heterogeneous because of JavaScript's dynamic typing and probably other reasons.
Arrays in JavaScript use integer indices, but Objects in JavaScript represent key value pairs. These are what you want to use. You can have Arrays of Objects, and Object properties can contain arrays (and other objects).
myArray = [];
myArray[5] = {name: "Jack", age: "38", location: "Australia"};
console.log(myArray[5].name); // could also use ["name"]