Because the error Can not read property '0' of undefined in a two-dimensional array

0

Hello everyone I have the Error mentioned when I want to store data, I keep in a coordinate arrangement and then when I want to store it, it says Error .

//Declaracion de variables
var coordinates = [];
var valid = 1;

function addMarker(location) 
{
  if (valid < 6) 
  {
    valid++;
      var marker = new google.maps.Marker(
    {
      position: location,
      map: map
    });
    markers.push(marker);
    var coordinate = [location.lat(), location.lng()];
    coordinates.push(coordinate);
    console.log(location.lat() + ', ' + location.lng())
    console.log(coordinates);
    console.log(markers);
    alert(location);
  }
  else
  {
    alert('No puedes agregar mas puntos de encuentro');
  }

}//addMarker

function registerSpots()
{
  console.log('POSTING spots...');
  for (var i = 1; i <= valid; i++) 
  {
    //create request
    var x = new XMLHttpRequest();
    //prepare request
    console.log(sessionStorage.userId);
    x.open('POST', '', true);
    //form data
    var fd = new FormData();
    fd.append('student', sessionStorage.userId);
    fd.append('slot', i);
    fd.append('latitude', coordinates[i][0]);
    fd.append('longitude', coordinates[i][1]);
    console.log(fd);
    x.send(fd);
    console.log(fd);
    x.onreadystatechange = function() 
    {
      if (x.status == 200 && x.readyState == 4) 
      {

        var JSONdata = JSON.parse(x.responseText); console.log(JSONdata);
        alert(JSONdata.errorMessage);
        //show buildings
        console.log(x.responseText);
      }//if
    }//x.onreadystatechange
  }//For
}//RegisterSpots

The error marks it here

fd.append('latitude', coordinates[i][0]);

Thank you in advance for reading

    
asked by Thunder 28.11.2017 в 02:11
source

1 answer

1

Your variable valid goes from 1 to 5. Your fix coordinates goes, therefore, from 0 to 4 (the arrays start from zero in js ... and in almost all languages except SQL and its relatives).

When you do:

for (var i = 1; i <= valid; i++) {
   ... operación con coordinates[i]...
}

First, you are omitting element 0 from the array, and second you are asking coordinates[5] which is undefined and therefore does not have an element [0].

You should do:

for (var i = 0; i < coordinates.length; i++) {
   ... operación con coordinates[i]...
}

or better yet

var coords_length = coordinates.length;
for (var i = 0; i < coords_length; i++) {
   ... operación con coordinates[i]...
}

comment to the margin: I do not see where you are defining markers .

    
answered by 28.11.2017 / 12:11
source