1

I am trying to create a function that upon each call it chooses the next variable in an array.

var nexttest=['abc','def','ghi'];
function nexttest() {
 if (nexttest = 'abc') {
  $('#result').load('url1.html');
 }
 else if (nexttest = 'def') {
  $('#result').load('url2.html');
 }
 else {
  $('#result').load('url3.html');
 }
}

Is there a way to make nexttest() use abc the first time, def the second time, and ghi the third time.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • Do you really mean just one `=` in `if` and `else if`?? – elclanrs Aug 08 '12 at 03:53
  • Although either of the approaches that have already been provided would work fine if you don't need to maintain the nexttest array you could just pop values off each time you call your function. http://stackoverflow.com/questions/1590247/how-do-you-implement-a-stack-and-a-queue-in-javascript – Carth Aug 08 '12 at 04:05

2 Answers2

3

You would create a variable that keeps track of the index of the array:

var index = 0;

Then, in the function, you could select the array element you want to interact with using the index variable:

var interactWithThis = nexttest[index];

And then increment the index each time the function is called:

index++;
jeff
  • 8,300
  • 2
  • 31
  • 43
1

I'd do it more like

var tester = function(){
    var i = 0;
    var tests = ['abc','def','ghi'];
    this.nexttest = function() {
        if (tests[i] == 'abc') {$('#result').load('url1.html');}
        else if (tests[i] == 'def') {$('#result').load('url2.html'); }
        else { $('#result').load('url3.html');}        
        i++;
    };
}

var testing = new tester();

testing.nexttest();
testing.nexttest();
testing.nexttest();
testing.nexttest();

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • Keith, thanks for your advice. Do you know how I would call this function from an iframe? I have been trying parent.testing.nexttest() and window.parent.testing.nexttest() but neither is working. – Devon Bessemer Aug 08 '12 at 05:38
  • 1
    Nevermind. parent.testing.nexttest() works fine, it was just the difference in protocols messing it up because I was viewing my site with SSL and loading the iframe with http://...oh well, figured it out now (time wasting done.) – Devon Bessemer Aug 08 '12 at 05:48