How to get values from an array without array.push

0

I'm trying to get a user's location and it keeps updating from time to time, searching, I found this method, but I can not just do this with the current value of the array, it concatenates (push) and adds infinitely .. does anyone know how I can fix this?

 var array = [];
   navigator.geolocation.watchPosition(function(position) {
   var lat = position.coords.latitude;
   var lon = position.coords.longitude;
   var vel = position.coords.speed;
   array.push(lat, lon, vel); 
   locationCode()  
});

function locationCode() {
   console.log(array)
   alert(array[0]);
}
    
asked by anonymous 06.05.2018 / 23:09

1 answer

1

Just one explanation:

var array = []; //Cira o array
navigator.geolocation.watchPosition(function(position) {
   array = []; //Zera o array

   //Cria variáveis com os valores
   var lat = position.coords.latitude;
   var lon = position.coords.longitude;
   var vel = position.coords.speed;

   //Adiciona os valores ao array
   array.push(lat, lon, vel);

   //Chama uma função que mostra os dados
   locationCode()  
});

function locationCode() {
   console.log(array)
   alert(array[0]);
}

You can do a little leaner:

let array = [];

navigator.geolocation.watchPosition(function(position) {
    array = [position.coords.latitude, position.coords.longitude, position.coords.speed];

    alert(array);
    console.log(array);
});
    
06.05.2018 / 23:37