0

i have a problem with my javascript code. I fill an array with jquery and i read it after with this code:

<script type="text/javascript">
var articulos = [''];
var i = 0;
  $.ajax({
        url: "getFiles.php",
        dataType: "json",
        success: function (data) {
            $.each(data, function(i,filename) {
                articulos[i] = filename;
                i++;
                //articulos.push(filename);
            });
        }
    });
  for (x=0;x<articulos.length;x++){
    var titleLength = articulos[x].length;
    if(titleLength != 0){
        alert(articulos[x]);
    }
  }
 </script>

jquery fill the array with three elements ("element1", "element2" and "element3").

Ok, mi first problem is that if i dont add a "blank" element in the array, i dont get results.

With this i get results (this blank element and the others)

var articulos = [''];

With this i dont get any result

var articulos = [];

My second problem is when i read the array. If i add this code, i dont get any alert

for (x=0;x<articulos.length;x++){
    var titleLength = articulos[x].length;
    if(titleLength != 0){
        alert(articulos[x]);
    }
  }

But if i add this code, i get 7 alerts correctly ("0", "8", "element1", "8", "element2", "8", "element3")

for (x=0;x<articulos.length;x++){
    var titleLength = articulos[x].length;
    alert(titleLength);
    if(titleLength != 0){
        alert(articulos[x]);
    }
  }

I dont understand why the if condition work only if i add an alert after.

Thanks in advance and sorry for my bad english

Javier
  • 103
  • 11
  • to populate an array use [`array.push(value)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) – Pedro Estrada May 23 '15 at 17:06
  • 1
    How ever it's not recommended but you should use `async:false`. – Roman C May 23 '15 at 17:10
  • 2
    since you are making an asynchronous call, you are not reading the array after. you are reading it before your JSON returns. – fbas May 23 '15 at 17:10
  • 2
    When you put the alert in for "zero" it delays / stops your code and you have to click on the "OK", this gives time for the async function to come back with results and fill the array. When you press OK the code resumes but as there are now results you can loop through them. Without the Alert the code hits the check for articulos.length very quickly and its value is only 1 (the '' that you inserted).... – Code Uniquely May 23 '15 at 17:15
  • Im idiot Its a litle process, so i will use the async:false Thank so much friend – Javier May 23 '15 at 17:32

0 Answers0