2017-04-07 87 views
1

首先我是java腳本新手。使用Javascript添加數組元素

我想將變量插入到包含經度和緯度的動態數組中。希望有幫助...

var locations = [ 
    [ test, test1], 
    [ -33.923036, 151.259052], 
    [ -34.028249, 151.157507], 
    [ -33.80010128657071, 151.28747820854187], 
    [-33.950198, 151.259302 ] 
]; 

var test = -33.923036; var test1 = 151.259052;

在此先感謝。

+0

問題是什麼?什麼是'console.log(locations)'? – Rayon

+0

locations.push(test); –

+0

我試着用數組拼接,但我沒有去知道如何將數組添加到另一個數組? –

回答

1

試試這個 -

您必須使用push方法將對象插入到數組中。

var test = -33.923036; var test1 = 151.259052; 
 

 
var locations = [ 
 
    
 
    [ -33.923036, 151.259052], 
 
    [ -34.028249, 151.157507], 
 
    [ -33.80010128657071, 151.28747820854187], 
 
    [-33.950198, 151.259302 ] 
 
]; 
 

 
locations.push([test, test1]) 
 

 
console.log(locations)

+1

*您必須使用push方法插入* - 您不必*使用該方法:'.push()'只是將元素添加到數組中的幾種方法之一,並注意它不像「append」那樣「插入」。 – nnnnnn

+0

是的。總是有很多選擇。當我讀到這個問題時,它就是我想到的:)謝謝 – Harsheet

0

您可以使用push方法在數組中添加新元素。

var newValues = [test,test1]; 
locations.push(newValues); 
+0

我們可以同時添加test和test1嗎?使用推 –

+0

更新了答案 –

+0

感謝它的工作 –

0

試試這個locations.push([variable_name_1,variable_name_2])

+0

感謝它的工作 –

0

你必須locations之前聲明testtest1

var test = 1, test1 = 2; 
 

 
var locations = [ 
 
    [ test, test1], 
 
    [ -33.923036, 151.259052], 
 
    [ -34.028249, 151.157507], 
 
    [ -33.80010128657071, 151.28747820854187], 
 
    [-33.950198, 151.259302 ] 
 
]; 
 

 
console.log(locations);

0
var test = -33.923036; var test1 = 151.259052; 
var locations = [ 
[ test, test1], 
[ -33.923036, 151.259052], 
[ -34.028249, 151.157507], 
[ -33.80010128657071, 151.28747820854187], 
[-33.950198, 151.259302 ] 
]; 

var locations = [ 
[ -33.923036, 151.259052], 
[ -34.028249, 151.157507], 
[ -33.80010128657071, 151.28747820854187], 
[-33.950198, 151.259302 ] 
]; 

locations.push([-33.923036,151.259052]) 

var test = -33.923036; var test1 = 151.259052; 

locations.push([test,test1]) 
console.log(locations); 
+0

'[\'$ {test} \','''{test1} \']'沒有任何意義:爲什麼要將值轉換爲字符串當所有其他數組項是數字? – nnnnnn

0

首先聲明你的變量

var test = -33.923036; var test1 = 151.259052; 

然後進行推

locations.push([test,test1]); 
0

對於一些價值的動態插入,你可以在陣列中把它包起來,你需要像以前訪問。

如果更改loc的內部值,則同樣會得到loations中的實際值,因爲您在loclocations[0]之間有一個參考。

只要不用locations[0]覆蓋locations[0],使用新的數組或原始值,就可以訪問實際值loc

var loc = [ 
 
     -33.923036, 
 
     151.259052 
 
    ], 
 
    locations = [ 
 
     loc, 
 
     [-33.923036, 151.259052], 
 
     [-34.028249, 151.157507], 
 
     [-33.80010128657071, 151.28747820854187], 
 
     [-33.950198, 151.259302 ] 
 
    ]; 
 

 
console.log(locations[0][0]); // -33.923036 
 
loc[0] = 42; 
 
console.log(locations[0][0]); // 42 
 
locations[0][0] = -10; 
 
console.log(locations[0][0]); // -10 
 
console.log(loc);    // [-10, 151.259052]

+0

感謝您的回答。 –