Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate an array in javascript

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
like image 735
Nithin Avatar asked May 22 '12 15:05

Nithin


People also ask

How do you iterate through an array?

Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

What is array iterator in JavaScript?

The most common iterator in JavaScript is the Array iterator, which returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary.


1 Answers

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]);
}
like image 194
Noah Freitas Avatar answered Sep 18 '22 15:09

Noah Freitas