tags:

views:

162

answers:

3

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;).

Thanks, Egil.

+8  A: 

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 beleive 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.

http://books.google.co.uk/books?id=f%5F2R9ra2PjEC&amp;pg=PA42&amp;lpg=PA42&amp;dq=javascript+unsigned+right+shift&amp;source=bl&amp;ots=jM4Y4Y3ZDS&amp;sig=fbHEe14PUaCYf1Wfq5TIX2tlW0I&amp;hl=en&amp;ei=4aWjSrXRJ56UjAfKuJmYDg&amp;sa=X&amp;oi=book%5Fresult&amp;ct=result&amp;resnum=3#v=onepage&amp;q=javascript%20unsigned%20right%20shift&amp;f=false

http://www.c-point.com/javascript%5Ftutorial/jsoprurshift.htm

pjp
Thanks, makes sense now. I did not realize that the length property could be anything but unsigned, javascript puzzles me at times :)
Egil Hansen
+2  A: 

The /*, from */ is an optional parameter. Notice var from = Number(arguments[1]) || 0; after that. If a second parameter was passed in the function call, the variable from will set to it.

Not sure about the unsigned right shift. Doesn't make any sense to me.

Ammar
+2  A: 

The /*, from*/ in the function declaration is just a comment by the author to say, that there’s a second optional parameter named from. It’s wrote as a comment so that it isn’t part of the signature (Array.prototype.indexOf.length returns 1).

And the right shift is probably used to always get an integer value of this.length.

Gumbo