开发者

push empty array as value of an array key [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help cla开发者_Python百科rifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜