为什么我执行的 Where 函数不起作用?
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
基本上,您需要 return 来自 boofunc
的值,而不仅仅是检查 prop % == 0
您实际上必须 return 它的结果。
接下来,您有几个拼写错误,例如 obj.prop
其中 obj
不存在,并且还设置 属性 为 that[prop] = val;
而不是 that.prop = val;
工作fiddle:https://jsfiddle.net/t32jywje/1/
我正在尝试实施 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
基本上,您需要 return 来自 boofunc
的值,而不仅仅是检查 prop % == 0
您实际上必须 return 它的结果。
接下来,您有几个拼写错误,例如 obj.prop
其中 obj
不存在,并且还设置 属性 为 that[prop] = val;
而不是 that.prop = val;
工作fiddle:https://jsfiddle.net/t32jywje/1/