2011-09-26 30 views
0

我需要將一個新數組作爲父數組鍵的值。將空陣列作爲數組鍵的值

這是我的數組。

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 
+1

請發佈您嘗試過的東西。 –

+0

然後它將是一個具有'hey'屬性的'Array'。 – alex

回答

4

相反new Array();,你應該只寫[]。你可以創建一個像這樣的嵌套數組

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

請記住,當你將東西推入數組時,它會被賦予一個數字索引。而不是asd[hey]因爲hey已被插入爲陣列中的第一項,所以請寫asd[0]

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不是arraymyArray實例。


如果你已經有一個數組的希望值鍵:

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