Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The output you've shown doesn't match either of the loops you've shown, but the gist seems to be that you don't want to see the <code>undefined</code> array entries.</p> <blockquote> <p>I understand why it happens, but I want use exactly jQuery $.each for my script.</p> </blockquote> <p>If you really want to do that, it's easy enough:</p> <pre><code>$.each(d, function(i, v){ if (d.hasOwnProperty(i)) { console.log(i); console.log(v); } }); </code></pre> <p>That will weed out the array indexes that don't exist in the array. You <em>could</em> use <code>typeof v[i] !== 'undefined'</code> but that will give you the incorrect result if you've actually set an array element to <code>undefined</code> (so it <em>exists</em>, but its value is <code>undefined</code>).</p> <p>jQuery is iterating over the array in the normal way, starting with index <code>0</code> and going through to index <code>length - 1</code>. The <code>for..in</code> loop loops over the properties in the object, and so doesn't loop for non-existant array entries (but <em>will</em>, the way you've written it, pick up anything from <code>Array.prototype</code> that's enumerable; <a href="http://blog.niftysnippets.org/2010/11/myths-and-realities-of-forin.html" rel="nofollow">more here</a>).</p> <p>Ways to loop things:</p> <ol> <li><p><code>$.each</code>; see above.</p></li> <li><p>Specifically for arrays and array-like things, the staid but useful <code>for (index = 0; index &lt; v.length; ++index)</code>. In this case, because the array is sparse, you'll want <code>v.hasOwnProperty(i)</code> or <code>typeof v[i] !== 'undefined'</code> (if you don't care about the case I listed above) to make sure you're seeing an entry that exists.</p></li> <li><p>For objects in general (including arrays, but you have to be careful): <code>for..in</code>:</p> <pre><code>for (propName in v) { // Check whether `v` has the property itself, or inherited it if (v.hasOwnProperty(propName)) { // `v` has the property itself // If looping an array or array-like thing and you want to see // only the *elements* (properties with numeric indexes) and // skip any non-element properties: if (String(parseInt(propName, 10)) === propName) { // It's an array element } } } </code></pre></li> </ol>
 

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