I have an array:
var arr = Array()
I wish to make this a multidimensional array, but I wish to pass in the keys dynamically.
Is there a way to do this?
p.addArrayKey = function(key){
arr.key.push('something');
}
You have not really explained what you mean by "multidimensional array". Multidimensional means that your elements would need to be accessed via more than one index. Example:
arr[ 3, 4 ] = ...; // tells us that arr is a 2-dimensional array
arr[ 4, 5, 1 ] = ..; //.....3-dimensional array
arr[ key ] = 'something'; // is a one-dimensional array!!
But yes, you can use a key as an index as follows. You cannot use the dot
notation because key
is a variable. And since you have the index, key
, you don't use push but you can assign the value directly:
arr[ key ] = 'something';
So that your method is:
p.addArrayKey = function(key, something){
arr[ key ] = something;
};
And you can call it like so:
p.addArrayKey ( 'mykey', 'something' );
And the output would be:
[mykey: "something"]
However if something
is the key you want to create in the array:
arr.something = 'initial value'; // or
arr[ 'something' ] = 'initial value'; //
Should work just fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.