Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

This question already has an answer here:

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);
}
share|improve this question

marked as duplicate by Frédéric Hamidi javascript Jun 10 '14 at 19:06

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
document.write(myArray[element]); – juvian Jun 10 '14 at 19:04
2  
^ noooooooooooo (document.write()) – Sterling Archer Jun 10 '14 at 19:04
    
    
and even this stackoverflow.com/questions/500504/… – maandoo Jun 10 '14 at 19:08
    
@Srinath, so, you don't like my duplicate? ;) – Frédéric Hamidi Jun 10 '14 at 19:08
up vote -1 down vote accepted

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

share|improve this answer
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]'.

share|improve this answer
    
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.