0

I have a question about proper syntax in iterative functions. I want to compare one master array to a large set (180+) of other arrays. The large set of arrays to be compared are systematically named (scorespec1, scorespec2, scorespec3...). Each comparison will be made not one-to-one but through an algorithm and then have the results stored in another set of arrays that are also systematically named for later query. I not worried about getting the algorithm right just yet. I'm just not sure of the proper syntax to iterate through my arrays. For instance, this is but one of the syntax structures I have tried but failed to get working:

for (i=01;i=186;i++){
  if (scorespec+(i)[04]=unknownspec[16]){
    resultarray+(i)[01]=True;
  else
    resultarray+(i)[01]=False;}}

My main problem here is I don't know how to structure the syntax to include the counter variable in my for-loop in the variable name. I've tried a variety of different syntaxes in addition to what I show above and it just doesn't seem to work right. What syntax should I be using?

WyoBuckeye
  • 187
  • 2
  • 13

2 Answers2

0

There are three parts to the for statement:

for ([initialExpression]; [condition]; [incrementExpression]) {
    // The statement (i.e. what will happen on each iteration)
}

To iterate through an array, we need the length of the array and a counter which will move towards that length as we iterate. This is the usual pattern:

var myArray = ['foo', 'bar', 'far']; //...

for (var i = 0; i < myArray.length; i++) {
    myArray[i]; // <- this is the current array item
}

It's sensible to cache the array's length like so:

for (var i = 0, l = myArray.length; i < l; i++) {
    myArray[i]; // <- this is the current array item
}

Also, FYI, your booleans, true and false, should not be capitalised.

James
  • 109,676
  • 31
  • 162
  • 175
  • Thanks for the tip on the capitalization. However, I'm not trying iterate through the items in an array, but through a set of arrays with similar names (scaorespec1, scorespec2, scorespec3...) Thank you. – WyoBuckeye Dec 30 '11 at 15:13
0

If you had declared your array in global scope you could access them using the window object:

var scorespec1 = "123";
var scorespec2 = "456";

for ( var i = 1; i < 3; i++ ){
  alert(window['scorespec' + i]);
}

Or you could use the slow and evil eval:

var scorespec1 = "123";
var scorespec2 = "456";

for ( var i = 1; i < 3; i++ ){
  var scorespec;
  eval("scorespec = scorespec" + i);
  alert(scorespec);
}
jantimon
  • 36,840
  • 23
  • 122
  • 185
  • But what about when the variables are arrays? For instance should I use this syntax? alert(window['scorespec' + i[01]]) – WyoBuckeye Dec 30 '11 at 15:29