2009-11-25 45 views
3

为什么我在犀牛中不能使用Array.filter()在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); 

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

+0

您使用的是什么版本的Rhino?当我在1.7中运行它时,我得到了两种情况下的“函数”(除非您更改数组,否则它们的方式完全相同)。 – 2009-11-25 19:49:16

+0

我在哪里可以看到版本? – 2009-11-26 13:15:07

+0

当您以交互方式启动它(即没有要运行的文件)时,它应该在启动时打印该版本。 – 2009-11-26 23:29:55

回答

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

谢谢:)我不知道'过滤器'不是标准的一部分。 – 2009-11-25 16:57:41

+2

是的,但是它是犀牛的一部分,因为Rhino实现了Mozilla维护的__JavaScript__语言,而不是ECMAScript。提问的人必须使用过时的Rhino版本。 – 2009-11-26 02:48:23

1

是过滤标准的JavaScript?它仅在Mozilla 1.8以上版本(大约this reference告诉我)

4

您正在使用过时版本的Rhino,它没有实现JavaScript 1.6。尝试Rhino 1.7