42

Okay, take it easy on me. I am really new to JavaScript and having issues getting the for-each loop to work correctly. Any Tips?

var array = ["Bob", "Nancy", "Jessie", "Frank"];
var arrayLength = myStringArray.length;

for (var i = 0; i < arrayLength; i++) {
    document.write(array);
}
ChaseHardin
  • 1,999
  • 7
  • 27
  • 49

2 Answers2

6
var myArray = ["Bob", "Nancy", "Jessie", "Frank"];
var arrayLength = myStringArray.length;

for (var i = 0; i < arrayLength; i++) {
    //Do something with element myArray[i]
}

I guess you need something like this.

Edit: Your array has only 4 elements. In the 2nd line I save the length of your array (4 elements --> length is 4) in the variable 'arrayLength'. Then I wrote a simple for-loop which cycles the 'i' from 0 till 3 so you can access your elements from your array as 'myArray[i]'.

Michel Michels
  • 1,630
  • 2
  • 10
  • 16
  • Please explain your answers. While this is sort of right (I don't condone document.write() advocation), the OP may have no idea what the difference is – Sterling Archer Jun 10 '14 at 19:09
2

The for in is used to iterate over properties on the object. It is not the same as a regular foreach. Use a for loop for this

TGH
  • 37,937
  • 11
  • 96
  • 131