admin管理员组

文章数量:1317906

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

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
Share Improve this question edited Nov 20, 2016 at 21:36 P.S. 16.4k14 gold badges65 silver badges86 bronze badges asked May 22, 2012 at 15:53 NithinNithin 2551 gold badge6 silver badges16 bronze badges 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? – Felix Kling 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/en/document.write – Felix Kling Commented May 22, 2012 at 16:05
Add a ment  | 

2 Answers 2

Reset to default 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]);
}

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

本文标签: How to iterate an array in javascriptStack Overflow