How to add variable to [JS] array

Asked

Viewed 243 times

2

I have the following code:

var newLat = markerElem.getAttribute('lat');
var newLng = markerElem.getAttribute('lng');

var locations = [
    {lat: newLat, lng: newLng}
]

I want to take the values of the variables newLat and newLng and store them within the array locations as values of their respective indices.

EXAMPLE

I want the variable values passed newLat and newLng for the array indexes lat and lng, being like this:

var newLat = 123;
var newLng = 321;

var locations = [
    {lat: 123, lng: 321}
]
  • I don’t understand can you explain better?

  • Can you improve the explanation? You want to add variables to the array or create an array of variables?

  • Let me give you an example to make it clear

  • 1

    If your wish is to add to the do &#Xa array;locations.push({ lat: newLat , lng: newLng}); javascript will add a new input to your array and then to retrieve it just go through it.

  • Lucas Brogni, your code worked, I just had to pass the values to float. Reply to my post with this comment to mark it as solved.

  • @Higorcardoso answered there. Hehe

Show 1 more comment

2 answers

3

You can change the values this way:

var locations = [
    {lat: '', lng: ''}
]

var markerElem = document.getElementById("div");
var newLat = markerElem.getAttribute('lat');
var newLng = markerElem.getAttribute('lng');

locations[0].lat = newLat; // altera lat
locations[0].lng = newLng; // altera lng

console.log(locations);
<div id="div" lat="123" lng="456"></div>

locations[0] selects the first index of the array.

If you want to add a new index to the array, you can do so:

var locations = [];

var markerElem = document.getElementById("div");
var lat = markerElem.getAttribute('lat');
var lng = markerElem.getAttribute('lng');

locations.push({ lat , lng });

console.log(locations);
<div id="div" lat="123" lng="456"></div>

By just entering the variable name, the name and value are already added of the variable as the object key in the array.

2


If your wish is to add to the array do

locations.push({ lat: newLat , lng: newLng});

Javascript will add a new input to your array and then to retrieve it just go through it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.