No Array.filter() in Rhino?

旧城冷巷雨未停 提交于 2020-01-02 07:24:25

问题


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:


There is no standardized filter function for Javascript Arrays, it is only an extension to the standard. (There is as of the ES5 spec published just a month after this answer was posted.) 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;
  };
}



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/1798290/no-array-filter-in-rhino

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!