I was looking in the javascript reference manual on the indexOf page at developer.mozilla.org site, and noticed a few things in their implementation code of indexOf, I hope somebody can explain to me.
To save everybody a round trip to the mozilla site, here is the entire 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;
  };
}
What I do not understand is the /*, from*/ in the function declaration, and the zero-fill right shift >>> in the extracting of the length of the array (var len = this.length >>> 0;).
The /*, from */ is a commented out parameter. However it looks like it has been left in the comments to show that this parameter can optionally be specified for the function.
var from = Number(arguments[1]) || 0;
I believe that arguments[1] would be the from value if passed in.
The arguments array is especially useful with functions that can be called with a variable number of arguments, or with more arguments than they were formally declared to accept. http://www.devguru.com/Technologies/Ecmascript/Quickref/arguments.html
The >>> is an unsigned right shift. It's being used here to convert a potentially signed number length into an unsigned number.
Extract from Professional JavaScript for Web Developers
http://www.c-point.com/javascript_tutorial/jsoprurshift.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With