Javascript Rhino中没有Array.filter()?
为什么我不能在Rhino中使用Javascript Rhino中没有Array.filter()?,javascript,rhino,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); 这两种情况都输出“未定义”。Javascript数组没有标准化的过滤器函数,它只是
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);
这两种情况都输出“未定义”。Javascript数组没有标准化的过滤器
函数,它只是标准的扩展。(在这个答案发布一个月后,ES5规范就发布了。)提供了一个兼容性示例,用于那些不支持它的实现
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;
};
}
if(!Array.prototype.filter)
{
Array.prototype.filter=函数(fun/*,thisp*/)
{
var len=this.length>>>0;
如果(乐趣的类型!=“功能”)
抛出新的TypeError();
var res=新数组();
var thisp=参数[1];
对于(变量i=0;i
过滤器是标准javascript吗?它只在Mozilla中出现,因为1.8版(或者这么说)告诉我您使用的是一个过时的Rhino版本,它没有实现JavaScript 1.6。试试看。谢谢:)我不知道过滤器不是标准的一部分。是的,但它是Rhino的一部分,因为Rhino实现了JavaScript,由Mozilla维护的语言,而不是ECMAScript。问这个问题的人一定是用了过时的Rhino版本。你用的是什么版本的Rhino?当我在1.7中运行它时,两种情况下我都会得到“函数”(顺便说一句,它们完全等效,除非你改变数组)。当你以交互方式启动它时(即没有要运行的文件),它应该在启动时打印版本。Rhino 1.5 release 4 2003 01 16
-非常旧,我现在会更新它,希望还能提高速度:)