现在的位置: 首页 > 综合 > 正文

ReoScript引擎的Lambda表达式

2018年05月27日 ⁄ 综合 ⁄ 共 720字 ⁄ 字号 评论关闭

javascript作为一种脚本语言,lambda表达式跟闭包这种特性都是天然支持的.那么在ReoScript引擎中实现这些特性就不是什么难事

下面的示例实现了C# 中 Lambda表达式中的一些功能,其下的代码已经经过本人亲自测试,可以完美运行~!

做加法运算的Lambda表达式

var plus = (a, b) => a + b;
plus(1, 2);

结果为3

做Sum运算的Lambda表达式

Array.prototype.sum = selector => {
    var total = 0;
        
    for(element in this) {
    total += (selector == null ? element : selector(element));
    }
    return total;
};

function Sales(year, amount) {
    this.year = year;
    this.amount = amount;
}
      
var arr = [ new Sales(2005, 130),
            new Sales(2006, 100),
            new Sales(2007, 210),
            new Sales(2008, 190), ];

arr.sum(obj => obj.amount);

结果为630

做Where过滤的Lambda表达式

Array.prototype.where = predicate => {
    var result = [];
        
    for(var element in this)
    if(predicate(element))
        result.push(element);

    return result;
};

var arr = [1, 2, 5, 7, 8, 10, 12, 15, 17, 18, 19];
var result = arr.where(n => n > 10);

结果为[12, 15, 17, 18, 19]

抱歉!评论已关闭.