9

I have an array like var arr = { 30,80,20,100 };

And now i want to iterate the above array and add the iterated individual values to one function return statement for example

function iterate()
{
    return "Hours" + arr[i];
}

I had tried in the following approach

function m()
{
    for(var i in arr)
    {
        s = arr[i];
    }
    document.write(s);
}

The above code will gives only one value i.e. last value in an array. But i want to iterate all values like

30---for first Iteration
80---for second Iteraton

Any help will be appreciated
2
  • 5
    In each iteration you are overriding s with arr[i]. Since s can only be one value, what did you expect s to be after the loop? Commented May 22, 2012 at 15:59
  • You should also be aware of what document.write is doing after the DOM is loaded: developer.mozilla.org/en/document.write Commented May 22, 2012 at 16:05

2 Answers 2

2

Iterate over using the length property rather than a for ... in statement and write the array value from inside the loop.

for (var ii = 0, len = arr.length; ii < len; ii++) {
  document.write(arr[ii]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Out of interest, why ii and not just i?
@Jivings: Why not? You can name a variable anything.
@Jivings It's an old habit that I picked up from one of my teachers. I think the logic was that ii is easier to find and replace than just i. I don't think I've ever had to use it, but it has become habit at this point.
1

That's because your write statement is outside the loop. Don't you want it like this?

function m(arr) {
    for (var i = 0; i < arr.length; i++) {
        s = arr[i];
        document.write(s);
    }

}​

Also, don't use in because it will give you ALL the properties of array. Use array.length

2 Comments

Thanks for your reply. The thing is i want to access the array out side of the loop .
@Nithin: Then you should have asked your question properly and precisely. But I think you gain more from reading the MDN JavaScript Guide, especially about arrays. You have to at least learn the basics of a language before you can use it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.