2017-04-07 99 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

感谢您的回答。 –