push empty array as value of an array key [closed]
I need to push a new array as the value of a parent array key.
this is my array.
asd[
[hey],
[hi]
]
i would like to return.
asd[
[hey]=>[],
[hi]
]
i do:
var asd = new Array();
asd.push(hey);
asd.push(hi);
asd[hey].push(new Array());
so obviously is not ok my code
Instead of new Array();
you should just write []
. You can create a nested array like this
myarray =
[
"hey",
"hi",
[
"foo"
]
]
Remember that when you push things into an array, it's given a numerical index. Instead of asd[hey]
write asd[0]
since hey
would have been inserted as the first item in the array.
You could do something like this:
function myArray(){this.push = function(key){ eval("this." + key + " = []");};}
//example
test = new myArray();
//create a few keys
test.push('hey');
test.push('hi');
//add a value to 'hey' key
test['hey'].push('hey value');
// => hey value
alert( test['hey'] );
Take notice that in this example test
is not an array
but a myArray
instance.
If you already have an array an want the values to keys:
function transform(ary){
result= [];
for(var i=0; i< ary.length; i++){result[ary[i]] = [];}
return result;
}
//say you have this array
test = ['hey','hi'];
//convert every value on a key so you have 'ary[key] = []'
test = transform(test);
//now you can push whatever
test['hey'].push('hey value');
// => hey value
alert( test['hey'] );
In this case test
remains an array
.
精彩评论