0

I have a script that retrieves data from a WebSQL db, it then strips off the first letter of each record and builds an array to be displayed later.

I can only access the array in the for loop. Any help would be appreciated.

$(document).ready(function(e) {
  var init;
  var len;
  inits = [];

  var db = openDatabase("contacts", "1.0", "contacts database", 5 * 1024 * 1024);
  db.transaction(function(tx) {
    tx.executeSql("SELECT * FROM names", [], function(tx, results) {
      len = results.rows.length;
      $("#recordcount ").text(len + " records found");

      for (i = 0; i <= len; i++) {
        var str = results.rows.item(i).lname;
        init = str.substring(0, 1);
        if ($.inArray(init, inits) !== -1) {} else {
          inits.push(init[i]);
        }
$.each(inits, function (index,value){
 alert(index + ":" + value);
});




      };
    });
  });
});

when trying to access inits, all I get is undefined unless I access it in the for loop.

console.log(inits)
VM112:1 ["H", undefined, undefined]

Thx.

peak
  • 105,803
  • 17
  • 152
  • 177
Dave
  • 43
  • 8

1 Answers1

0

There are a lot of things going on i don't quite understand why, placements etc..

anyways, give this a go. (sorry for removing the jquery)

  var init;
  var len;
  var inits = [];

  var db = openDatabase("contacts", "1.0", "contacts database", 5 * 1024 * 1024);
  db.transaction(function(tx) {
    tx.executeSql("SELECT * FROM names", [], function(tx, results) {
      len = results.rows.length;
      recordcount.innerHTML = (len + " records found");

      for (i = 0; i < len; i++) {
        var str = results.rows.item(i).lname;
        console.log('str: '+str);
        init = str.substring(0, 1);
        console.log('init: '+init);

        if(inits.indexOf(init) === -1){
            inits.push(init);
        }

      }
      inits.forEach(function( index, value ) {
        console.log(a);
      });

      //Done.
      logIt();
    });
  });
  function logIt(){
      console.log(inits);
  }
user2267175
  • 595
  • 5
  • 14
  • that did it, thanks. – Dave Oct 01 '16 at 14:53
  • so if anybody is interested, I went back through my code and the code from user2267175 line by line to see what was wrong. this is what I found. 'for(i=0;i<=len;i++){' should have been 'for(i=0;i – Dave Oct 01 '16 at 15:11