在Rhino中没有Array.filter()?

时间:2009-11-25 16:48:03

标签: javascript rhino

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

代码是这样的:

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

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

3 个答案:

答案 0 :(得分:4)

Javascript Arrays没有标准化的filter函数,它只是标准的扩展。 (在此之后一个月发布了ES5规范)回答已发布。) MDC reference page为您提供了一个兼容性示例,用于那些不支持它的实现......

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

答案 1 :(得分:4)

您使用的是过时的Rhino版本,但未实现JavaScript 1.6。试试Rhino 1.7

答案 2 :(得分:1)

过滤标准javascript?它只在Mozilla中出现1.8(左右this reference告诉我)

相关问题