Dave Dave - 2 months ago 8
Javascript Question

can't access array outside of loop in js

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.

Answer

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);
  }
Comments