我正在尝试实现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
)。或者是否有更好的方法来获取现有对象的过滤版本?
答案 0 :(得分:1)
试试这个:
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;