views:

80

answers:

3

Why can't I use Array.filter() in Rhino?

The code is like this:

var simple_reason = ["a", "b", "c"];
print(typeof simple_reason.filter);

var not_so_simple_reason = new Array("a", "b", "c");
print(typeof not_so_simple_reason.filter);

Both cases output "undefined".

+1  A: 

There is no standardized filter function for Javascript Arrays, it is only an extension to the standard. The MDC reference page gives you an compatibility sample to use for those implementations that do not support it...

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}
Josh Stodola
Thanks :) I didn't know `filter` wasn't part of standard.
Kuroki Kaze
Yes, but it _is_ part of Rhino because Rhino implements __JavaScript__, the language maintained by Mozilla, not ECMAScript. The person who asked the question must be using an outdated version of Rhino.
Eli Grey
+1  A: 

Is filter standard javascript? It is only in Mozilla since 1.8 (or so this reference tells me)

Victor
+1  A: 

You are using an outdated version of Rhino that does not implement JavaScript 1.6. Try Rhino 1.7.

Eli Grey