2

I've encountered this code in a codebase to add the indexOf function :

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

This is a different implementation to the one recommended by Mozilla https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf :

Code:

   if (!Array.prototype.indexOf) {  
        Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {  
            "use strict";  
            if (this == null) {  
                throw new TypeError();  
            }  
            var t = Object(this);  
            var len = t.length >>> 0;  
            if (len === 0) {  
                return -1;  
            }  
            var n = 0;  
            if (arguments.length > 0) {  
                n = Number(arguments[1]);  
                if (n != n) { // shortcut for verifying if it's NaN  
                    n = 0;  
                } else if (n != 0 && n != Infinity && n != -Infinity) {  
                    n = (n > 0 || -1) * Math.floor(Math.abs(n));  
                }  
            }  
            if (n >= len) {  
                return -1;  
            }  
            var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);  
            for (; k < len; k++) {  
                if (k in t && t[k] === searchElement) {  
                    return k;  
                }  
            }  
            return -1;  
        }  
    }  

Should I be using the Mozilla version instead or will version mentioned at beginning of question suffice ? Are there advantages of using one over the other ?

blue-sky
  • 51,962
  • 152
  • 427
  • 752

2 Answers2

2

I'd suggest using Mozilla version on indexOf. It's quite similar to the first implementation, but is more polished (which is not surprising, actually). For example, it will return -1 right as it finds out that given array is empty, and will correctly process different edge values given as a second parameter.

Or better yet, if you use jQuery (as it is implied by your tags choice), why don't just use its $.inArray() method?

raina77ow
  • 103,633
  • 15
  • 192
  • 229
2

They're both from MDN but the first version is from an older version of the indexOf page. The newer version is an update to bring the implementation in line with the algorithm published in the ECMAScript 5 spec. Given all that, it seems reasonable to use the newer version.

Here's the diff on the MDN page where the change was made:

https://developer.mozilla.org/index.php?title=en/JavaScript/Reference/Global_Objects/Array/indexOf&action=diff&revision=32&diff=33

Tim Down
  • 318,141
  • 75
  • 454
  • 536