简体   繁体   English

访问 javascript 中的全局变量时出现问题

[英]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.我期望 myvar 表现为全局变量,但事实并非如此。 I cannot get any values for myvar in the initialize().我无法在 initialize() 中获取 myvar 的任何值。

What am I doing wrong here?我在这里做错了什么?

pseudo-schmeudo.伪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/小提琴: 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当您调用 initialize() - 它会以 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/我不确定您要完成什么,但我能够进行一些修改并能够在此示例中访问全局变量: 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这是我唯一能想到的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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