2015-11-13 76 views
1

我正在拼命用我的多維數組。我實際上已經完成了幾個小時的研究,但找不到任何有用的東西。推多維數組

我有一個多維數組,看起來像這樣:

var locations = [ 
    ['Bondi Beach', -33.890542, 151.274856, 4, 0], 
    ['Coogee Beach', -33.923036, 151.259052, 1, 1], 
    ['Cronulla Beach', -34.028249, 151.157507, 3, 2], 
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 2, 0], 
    ['Maroubra Beach', -33.950198, 151.259302, 5, 2] 
]; 

現在我想要的東西添加到陣列推,如:


locations.push(DATA HERE); // 'Cronulla Beach 2', -34.028249, 151.157507, 8, 7 

應該看哪個像這在最後:

var locations = [ 
    ['Bondi Beach', -33.890542, 151.274856, 4, 0], 
    ['Coogee Beach', -33.923036, 151.259052, 1, 1], 
    ['Cronulla Beach', -34.028249, 151.157507, 3, 2], 
    ['Manly Beach', -33.80010128657071, 151.28747820854187, 2, 0], 
    ['Maroubra Beach', -33.950198, 151.259302, 5, 2], 
    ['Cronulla Beach 2', -34.028249, 151.157507, 8, 7] 
]; 

注意:我需要一個數組,因此如果它是一個對象的解決方案,它不會幫助我。

最好的解決方案還應該工作,如果陣列仍然是空喜歡locations[];

回答

1

只要把合作在另一個陣列中,並將其推入locations陣列,如

locations.push(['Cronulla Beach 2', -34.028249, 151.157507, 8, 7]); 
2

由於多維數組只是數組的數組,你可以通過只配售對象的方括號中列表中創建一個新的數組,你可以這樣做:

locations.push(['Cronulla Beach 2', -34.028249, 151.157507, 8, 7]); 

要訪問或修改現有的位置,使用其指數:

var location = locations[0]; 
console.log(location); 
locations[0][0] = "Bomba Beach"; // change name of first location 
locations[0][1] = -30.2; // change latitude of first location