开发者

How to increment a global variable inside a function?

The variable currentIndex is declared globally and initialized with a certain value say '0'. How do I hold the value of currentIndex which is incremented every time the function is called开发者_如何学运维? In the given code, every time the function is called, the value is reinitialized.

function nextSong(e:Event):void 
{
        sc.stop();

 currentIndex = currentIndex + 1;

 var nextSongFunc:URLRequest = new URLRequest(songlist[currentIndex].file);
 var nextTitle:Sound = new Sound();
 nextTitle.load(nextSongFunc);
 currentSound = nextTitle;
 sc = currentSound.play();

 sc.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

NextBtn.addEventListener(MouseEvent.CLICK, nextSong);


You need to declare the variable outside the function. How you do this depends on the context. Where is this function being defined? In the 'actions window' on the timeline in Flash? or inside a <script> block in Flex? or somewhere else?

It looks like you're in the Flash tool, in the actions window. If so, then just do it like this:

var currentIndex:int = 0;

function nextSong(e:Event):void {
  sc.stop();
  currentIndex = currentIndex + 1;

  var nextSongFunc:URLRequest = new URLRequest(songlist[currentIndex].file); 
  var nextTitle:Sound = new Sound(); 
  nextTitle.load(nextSongFunc); 
  currentSound = nextTitle; 
  sc = currentSound.play();

  sc.addEventListener(Event.SOUND_COMPLETE, nextSong); 
}

NextBtn.addEventListener(MouseEvent.CLICK, nextSong);

If that doesn't work, let me know some more details, and we'll sort it out.


If you're using Flash CS , you should take advantage of the DocumentClass. In such case you could define currentIndex as a private variable and it will be incremented/decremented in your functions.

This is a much better approach than writing your code in the Actions panel, allows for a lot more flexibility and you don't run into problems due to frame dependent code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜