2

The problem is I need to add a multi dimension array dynamically, please look at the following example:

var list = [];
var listname;
var height;
var width;

list.push(listname);
list[listname] = height;
list[listname] = width;

the code above is not what I expected , which should be [listname => [[0]=>height,[1]=>width]], what can I do if I do not want to create an array for listname, can I dynamic add a mulit dimension array ? thanks.

1
  • I don't understand, how do you want a multi-dimensional array without wanting to push an array into the array? Commented Mar 14, 2013 at 1:39

1 Answer 1

4

Don't confuse Arrays with Maps. They are different fundamental data-types1

var myLists = {};       // name => array
var listname = "stuff"; // why not?
var height = 1;
var width = 2;

// there is no Object.push, but we can assign a property by name
myLists[listName] = [height];
// then we can Array.push into the array we just assigned
myLists[listName].push(width);

Then, myLists:

{
   stuff: [1, 2]
}

1JavaScript mostly maintains this distinction - if one doesn't add random properties to Arrays or otherwise fake an Object to behave like an array.

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

3 Comments

if later I would like to check whether there is a key inside this object, all I need to do is if (myLists.hasownProperties('stuff'))? thx
@user782104 obj.hasOwnProperty(propName) or propName in obj (when not as for(x in y)) - but they do slightly different things. I prefer the latter (with in) for "existence testing" as it will look up the chain, if it ever matters, and it just "looks cleaner" to me. Also, obj[propname] is sometimes more appropriate, if the value (and whether or not it is truth-y) if also of importance.
@user782104 You're welcome. Unless one needs to use an array (i.e. has a sequence of values), I would likely write it like: myLists[listName] = {width: 2, height: 1} - it's nicer to give values names (via property names), if appropriate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.