Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use a sequential <code>for</code> loop:</p> <pre><code>var myStringArray = ["Hello","World"]; var arrayLength = myStringArray.length; for (var i = 0; i &lt; arrayLength; i++) { alert(myStringArray[i]); //Do something } </code></pre> <p>@zipcodeman suggests the use of the <code>for...in</code> statement, but for iterating arrays <code>for-in</code> should be avoided, that statement is meant to <strong>enumerate</strong> object properties.</p> <p>It shouldn't be used for array-like objects because:</p> <ul> <li>The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.</li> <li>Inherited properties are also enumerated.</li> </ul> <p>The second point is that it can give you a lot of problems, for example, if you extend the <code>Array.prototype</code> object to include a method there, that property will be also enumerated.</p> <p>For example:</p> <pre><code>Array.prototype.foo = "foo!"; var array = ['a', 'b', 'c']; for (var i in array) { alert(array[i]); } </code></pre> <p>The above code will alert, "a", "b", "c" and "foo!".</p> <p>That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).</p> <p>The <code>for-in</code> statement as I said before is there to <em>enumerate</em> object properties, for example:</p> <pre><code>var obj = { "a": 1, "b": 2, "c": 3 }; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety... alert("prop: " + prop + " value: " + obj[prop]) } } </code></pre> <p>In the above example the <code>hasOwnProperty</code> method allows you to enumerate only <em>own properties</em>, that's it, only the properties that the object physically has, no inherited properties.</p> <p>I would recommend you to read the following article:</p> <ul> <li><a href="http://web.archive.org/web/20101213150231/http://dhtmlkitchen.com/?category=/JavaScript/&amp;date=2007/10/21/&amp;entry=Iteration-Enumeration-Primitives-and-Objects" rel="noreferrer">Enumeration VS Iteration</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload