简体   繁体   中英

Why is this global variable not recognised in javascript function?

Despite excessive googling I just don't get why my function doSomething does nothing in the situation below. Any idea why it doesn't work?

Many thanks, Gordon

var arrAttend=new object();
arrAttend["Blob"]='hello';

function doSomething() {
alert (arrAttend["Blob"]);
}

It's a typo, you should use new Object (capital O). Or use an Object Literal :

var arrAttend = {Blob: 'hello'};

function doSomething() {
  alert (arrAttend.Blob);
}

Two problems :

  • object isn't defined
  • you don't call your function

Try this :

var arrAttend= {}; // that's the simplest way to create a new javascript object
arrAttend["Blob"]='hello';

function doSomething() {
   alert (arrAttend["Blob"]);
}
doSomething();

Note that the first kind of error is very easily found when you look at the console : an error is displayed. I'd suggest you to use developer tools (for example Chrome's ones ) so that you don't develop in the blind. BTW you'd see that using console.log instead of alert is most often more convenient.

Try this :

var arrAttend=new Object();
arrAttend["Blob"]='hello';

function doSomething() {
alert (arrAttend["Blob"]);
}

There's typo error in your code. And an object should be used like follow -

var arrAttend= {
        name:'Blob'
    };
function doSomething() {
alert (arrAttend.name);
}
      doSomething(); 

Try this:

// create object
var arrAttend=new Object();
arrAttend["Blob"]='hello';

function doSomething() {
alert (arrAttend["Blob"]);
}

// call function
doSomething();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM