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 Answers 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]);
}
3 Comments
ii and not just i?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.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
switharr[i]. Sincescan only be one value, what did you expectsto be after the loop?document.writeis doing after the DOM is loaded: developer.mozilla.org/en/document.write