newbie
newbie

Reputation: 428

Problem with Javascript object and accessing property which exists

I have something like this:

var test = {};

function blah() {
   test[2] = 'filled';
}

blah(); // ! Hopefully confusion is now averted..

console.log(test);
//result  test -> 2:"filled"

console.log(test[2]);
//result  undefined

I don't understand why I'm getting 'undefined' in the second instance when according to the first instance, the property of that object clearly exists!

Does anyone have any ideas?

Thanks

OK, it seems that folk are getting confused as to what context the code exists in, for clarity sake I have now added the call to the blah(). but please refer to the comment under Jeff B's response!

Here is an example of relevant code so to say:

mydb = ..... //gets created here with relevant credentials
var test = {};
mydb.transaction(
    function(transaction) {
     transaction.executeSql("select * from mytable;", [], function(transaction,result) { 
     var r = result.rows.item(0);
     test[2] = r.title;
}, errorHandler);
    });

    console.log(test);
    //result  test -> 2:"the title"

    console.log(test[2]);
    //result  undefined

@Dancrumb Your mention of the single-threadedness of Javascript gave me an idea, and I tried this:

window.setTimeout(function(){ alert(test[2]); },2000);

and it worked! I got the expected value to alert. Can you suggest how I can get around this without using a 'hack' like that above?

Upvotes: 2

Views: 243

Answers (3)

Russell Leggett
Russell Leggett

Reputation: 8883

This is pretty clearly an asynchronous issue. The simplest way of getting code to run after you set test[2], is to either put the code right there, or use another callback, and call it after you set test[2].

Upvotes: 0

Dancrumb
Dancrumb

Reputation: 27539

EDIT

I ran the following code:

mydb = openDatabase('note','','Example',1024);
var test = {};
mydb.transaction(
    function(transaction) {
     transaction.executeSql("select * from mytable;", [], function(transaction,result) { 
     var r = result.rows.item(0);
     test[2] = r.title;
}, errorHandler);
    });

    console.log(test);

    console.log(test[2]);

in Safari 4.0.5

I got the following:

Object
  No Properties

undefined

This is what I would expect to see. The object test does not have any properties assigned to it until the callback from mydb.transaction occurs and, since Javascript is single threaded, this cannot happen before the calls to console.log.

Since you're getting a different outcome, can you outline what browser and what version you are using?

Upvotes: 2

Jeff B
Jeff B

Reputation: 30099

Because you aren't calling blah()?

Also, you want:

var test = [];

or:

var test = new Array();

Upvotes: 2

Related Questions