3

为什么我不能Array.filter()在 Rhino 中使用?

代码是这样的:

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

两种情况都输出“未定义”。

4

3 回答 3

4

Javascript Arrays没有标准化filter的功能,它只是标准的扩展。 (在发布此答案后仅一个月发布了 ES5 规范。)MDC 参考页面为您提供了一个兼容性示例,可用于那些不支持它的实现......

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;
  };
}
于 2009-11-25T16:50:14.707 回答
4

您正在使用未实现 JavaScript 1.6 的过时版本的 Rhino。试试犀牛 1.7

于 2009-11-26T02:49:51.790 回答
1

过滤器是标准的javascript吗?自 1.8 以来它只在 Mozilla 中(或者这个参考告诉我)

于 2009-11-25T16:52:06.030 回答