Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, implement <code>indexOf</code> in JavaScript for browsers that don't already have it. For example, see <a href="http://erik.eae.net/playground/arrayextras/arrayextras.js" rel="noreferrer">Erik Arvidsson's array extras</a> (also, the <a href="http://erik.eae.net/archives/2005/06/05/17.53.19/" rel="noreferrer">associated blog post</a>). And then you can use <code>indexOf</code> without worrying about browser support. Here's a slightly optimised version of his <code>indexOf</code> implementation:</p> <pre><code>if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (obj, fromIndex) { if (fromIndex == null) { fromIndex = 0; } else if (fromIndex &lt; 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex, j = this.length; i &lt; j; i++) { if (this[i] === obj) return i; } return -1; }; } </code></pre> <p>It's changed to store the length so that it doesn't need to look it up every iteration. But the difference isn't huge. A less general purpose function might be faster:</p> <pre><code>var include = Array.prototype.indexOf ? function(arr, obj) { return arr.indexOf(obj) !== -1; } : function(arr, obj) { for(var i = -1, j = arr.length; ++i &lt; j;) if(arr[i] === obj) return true; return false; }; </code></pre> <p>I prefer using the standard function and leaving this sort of micro-optimization for when it's really needed. But if you're keen on micro-optimization I adapted the <a href="https://blogs.oracle.com/greimer/resource/loop-test.html" rel="noreferrer">benchmarks</a> that roosterononacid linked to in the comments, to <a href="http://obscurity.nfshost.com/x/bench.html" rel="noreferrer">benchmark searching in arrays</a>. They're pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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