开发者

Problem accessing global variable in javascript

I am wor开发者_开发百科king 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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜