[英]Why isn't my implementation of a Where function working?
我正在尝试实现Where
子句。 我的尝试
Object.prototype.Where = function ( boofunc ) {
// Returns an object whose own properties are
// those properties p of this object that satisify
// the condition boofunc(p)
var that = {};
for ( var prop in this )
{
var val = this[prop];
if ( boofunc(val) )
{
that.prop = val;
}
}
return that;
}
var obj = { x : 10, y : 11, z : 12 };
var evens = obj.Where(function(prop){obj.prop%2==0});
console.log(evens); // TEST
不起作用(打印到控制台的对象没有x
, y
或z
)。 还是有更好的方法来获取现有对象的过滤版本?
尝试这个:
Object.prototype.Where = function ( boofunc ) {
// Returns an object whose own properties are
// those properties p of this object that satisify
// the condition boofunc(p)
var that = {};
for ( var prop in this )
{
var val = this[prop];
if ( boofunc(val) )
{
that[prop] = val;
}
}
return that;
}
var obj = { x : 10, y : 11, z : 12 };
var evens = obj.Where(function(prop){ return prop % 2==0; });
console.log(evens); // TEST
基本上,您需要从boofunc
返回值,而不仅仅是检查prop % == 0
您实际上必须返回其结果。
接下来,您有一些输入错误,例如obj.prop
,其中obj
不存在,并且还设置了诸如that[prop] = val;
的属性that[prop] = val;
代替that.prop = val;
工作提琴: https : //jsfiddle.net/t32jywje/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.