简体   繁体   中英

Problem accessing global variable in javascript

I am working on google maps and I need to create an array of items. Here is my pseudo code:

<script>
var myvar=new array();

function initialize(){
   for i=1 to 10
   {  
        callAnotherFunct(i);
   }

   access myvar() here; 
}


function callAnotherFunct(i){
    myvar=array_element_i;
}

</script>

I am expecting myvar to behave as a global variable but it is not. I cannot get any values for myvar in the initialize().

What am I doing wrong here?

pseudo-schmeudo.

var myvar = [];

function initialize(){
   for (var i=0; i < 10; i++)
   {  
        callAnotherFunct(i);
   }

   alert(myvar[0]);
   alert(myvar[9]);
}


function callAnotherFunct(i){
    myvar[i]=i + 'pseudo-schmeudo';
}

initialize();

Fiddle-schmiddle .

fiddle: http://jsfiddle.net/AKKHB/

Seems to be ok

It is hard to tell what you might be doing wrong - with the pseudocode.

I have de-pseudified your code and it works fine:

var myvar=new Array();

function initialize(){
  for (i=1; i < 10; i++)
  {  
    callAnotherFunct(i);
  }
  alert(myvar);
  //access myvar() here; 
}

function callAnotherFunct(i){
  myvar.push(i);
}

when you call initialize() - it will alert with 1,2,3,4,5,6,7,8,9

Hope that helps

I am not sure what you were trying to accomplish, but I was able to make several modifications and was able to access the global variable in this example: http://jsfiddle.net/pKU6A/

var myvar=new Array(); //Array should be uppercase

function initialize(){
   for (var i=1; i < 10; i++) //incorrect for loop syntax
   {  
        callAnotherFunct(i);
   }

  alert(myvar);
}


function callAnotherFunct(i){
    myvar[i] = i; //local variable was not defined and index of array must be assigned
}

initialize(); //needed to call global function to kick it off
window.myvar = []; // don't use new Array()

function initialize(){
   for i=1 to 10
   {  
        callAnotherFunct(i);
   }

   //window.myvar or myvar here should work
}

I am guessing this is a namespace issue. Do something like this

window.project = window.project || {};
project.vars = project.vars || {};

Then you will have a namespace declaration, so you can do

project.vars.myVar = new Array();

That's the only issue I could think of

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