将空数组作为数组键的值

时间:2011-09-26 01:19:24

标签: javascript arrays

我需要将一个新数组作为父数组键的值。

这是我的阵列。

asd[
[hey],
[hi]

]

我想回来。

asd[
[hey]=>[],
[hi]
]

我做:

var asd = new Array();
asd.push(hey);
asd.push(hi);
asd[hey].push(new Array());

so obviously is not ok my code 

2 个答案:

答案 0 :(得分:4)

而不是new Array();,您应该只写[]。您可以像这样创建一个嵌套数组

myarray =
[
    "hey",
    "hi",
    [
        "foo"
    ]
]

请记住,当您将事物推入数组时,会给出一个数字索引。代替asd[hey]asd[0],因为hey将作为数组中的第一项插入。

答案 1 :(得分:1)

你可以这样做:

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'] );

请注意,在此示例中,test不是array,而是myArray实例。


如果您已经拥有一个数组,则需要键值:

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'] );

在这种情况下,test仍为array

相关问题