簡體   English   中英

為什么我的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

不起作用(打印到控制台的對象沒有xyz )。 還是有更好的方法來獲取現有對象的過濾版本?

嘗試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM