Javascript添加数组元素

时间:2017-04-07 06:08:56

标签: javascript arrays

首先,我是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;

提前致谢。

7 个答案:

答案 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 :(得分:0)

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

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

答案 2 :(得分:0)

试试这个locations.push([variable_name_1,variable_name_2])

答案 3 :(得分:0)

您必须在test之前声明test1locations



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




答案 4 :(得分: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);

答案 5 :(得分:0)

首先声明你的变量

var test = -33.923036; var test1 = 151.259052;

然后执行推送

locations.push([test,test1]);

答案 6 :(得分:0)

对于某些值的动态插入,您可以将其包装在数组中,您需要并像以前一样进行访问。

如果更改loc内的值,您也可以获得loations中的实际值,因为您在loclocations[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]