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);
}
4

2 Answers 2

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]'.

Sign up to request clarification or add additional context in comments.

1 Comment

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
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.