JavaScript 中是否有类似 C# 的 lambda 语法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7190439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:16:30  来源:igfitidea点击:

Is there a C#-like lambda syntax in JavaScript?

javascript

提问by élodie Petit

Is there a framework or post processor for JavaScript that supports lambda syntax like in C#?

是否有支持像 C# 中那样的 lambda 语法的 JavaScript 框架或后处理器?

Function definitions in CoffeeScript seem to look like lambdas but I have not looked into them thoroughly.

CoffeeScript 中的函数定义看起来像 lambda 表达式,但我没有深入研究它们。

Can anyone tell me, can I use lambda syntax in JavaScript?

谁能告诉我,我可以在 JavaScript 中使用 lambda 语法吗?

回答by Matthew Mcveigh

Lambda functions with similar syntax are included in ECMAscript 6, they're known as "arrow functions". An example:

具有相似语法的 Lambda 函数包含在ECMAscript 6 中,它们被称为“箭头函数”。一个例子:

["duck", "cat", "goat"].filter(el => el.length > 3);returns ["duck", "goat"]

["duck", "cat", "goat"].filter(el => el.length > 3);返回 ["duck", "goat"]

There's currently support in recent versions of Firefoxand Chrome.

目前支持FirefoxChrome 的最新版本。

To use this syntax in JavaScript that's targeting older browsers there are tools that can compile ES 6 to a more widely supported version - for example the tools Babelor Traceur.

为了在针对旧浏览器的 JavaScript 中使用这种语法,有一些工具可以将 ES 6 编译为更广泛支持的版本 - 例如工具BabelTraceur

回答by hans

You could use typescript (www.typescriptlang.org/):

您可以使用打字稿(www.typescriptlang.org/)

function (d, i) {
    return "translate(" + d.x + "," + d.y + ")";
}

would become

会成为

(d, i) =>  "translate(" + d.x + "," + d.y + ")"  

and much more cool stuff, like typing: ... that's if you are into that

还有更多很酷的东西,比如打字:...如果你喜欢的话

回答by Ruben-J

I started creating an extender for jQuery which does exactly the thing you are asking. JS-Lambda

我开始为 jQuery 创建一个扩展程序,它完全符合您的要求。 JS-Lambda

For example in C#:

例如在 C# 中:

  coll.TakeWhile(x => x.index < 3);

Looks like:

好像:

 $(coll).TakeWhile("x => x.index < 3");

回答by Morteza Tourani

Javascript has very nice anonymous functions that allows you to create lambdas anyWhere you need as a function but the implementation comes with some much words and scope creation repeating:

Javascript 有非常好的匿名函数,它允许您在任何需要的地方创建 lambdas 作为函数,但实现附带了一些单词和范围创建重复:

function(name){
     return "Hello, " + name;
}

Thanks to EcmaScript 2015 lambda expresion is now available for javaScript with simpler syntax as Arrow Function

感谢 EcmaScript 2015 lambda 表达式现在可用于具有更简单语法的 JavaScript箭头函数

(name) => "Hello, " + name

回答by seven

FIDDLE:https://jsfiddle.net/vktawbzg/

小提琴:https ://jsfiddle.net/vktawbzg/

NPM:https://www.npmjs.com/package/linqscript

NPM:https : //www.npmjs.com/package/linqscript

GITHUB:https://github.com/sevensc/linqscript

GitHub:https : //github.com/sevensc/linqscript

using Typescript i created a class List<T>which extends Array<T>

使用 Typescript 我创建了一个List<T>扩展的类Array<T>

usage:

用法:

var list = new List<ListView>();
...
var selected = list.Items.Where(x => x.Selected);

implementation:

执行:

 export class List<T> extends Array<T> {

    public Where(callback: (value: T) => boolean, thisArg?: any): List<T> {
            try {
                const list = new List<T>();

                if (this.length <= 0)
                    return list;

                if (typeof callback !== "function")
                    throw new TypeError(callback + ' is not a function');

                for (let i = 0; i < this.length; i++) {
                    const c = this[i];
                    if (c === null)
                        continue;

                    if (callback.call(thisArg, c))
                        list.Add(c);
                }

                return list;
            }
            catch (ex) {
                return new List<T>();
            }
        }
...
}

EDIT:I created a github repo: https://github.com/sevensc/linqscript

编辑:我创建了一个 github 仓库:https: //github.com/sevensc/linqscript

回答by Angel Fraga Parodi

Exact Matthew Mcveigh!!

正是马修麦克维!!

I want to contribute too, see this example

我也想贡献,看这个例子

"use strict";
/* Lambda Helper to print  */
function PrintLineForElement(element, index, array){
  document.write("a[" + index + "] = " + JSON.stringify(element)+"<br>");
}
/* function to print array */
function Print(a){
   a.forEach(PrintLineForElement)
   document.write("<br>");
}
/* user model */
class User{
  constructor(_id,_name,_age,_job){
    this.id = _id;
       this.name = _name;
    this.age = _age;
       this.job = _job;
  }
} 
/* Provaider users */
class UserService{ 

  constructor(){ } 
    
  GetUsers(){
        //fake ajax response
    let data = []; 
        data.push(new User(1,"Juan",20,"AM"));
        data.push(new User(2,"Antonio",20,"AM"));
        data.push(new User(3,"Miguel Angel",30,"Developer"));
        data.push(new User(4,"Bea",26,"AM"));
        data.push(new User(5,"David",24,"Developer")); 
        data.push(new User(6,"Angel",24,"Developer")); 
        data.push(new User(7,"David",34,"TeamLead"));
        data.push(new User(8,"Robert",35,"TeamLead"));
        data.push(new User(9,"Carlos",35,"TeamLead"));   
    
        return data;
  }
}

const userService = new UserService();
const users =  userService.GetUsers();

//get user order by name
document.write("All users </br>");
Print(users);

//get user order by name
document.write("Order users by name ASC : users.sort((a,b)=>{return a.name > b.name })</br>");
Print(users.sort((a,b)=>{return a.name > b.name; }));
document.write("Order users by name DESC : users.sort((a,b)=>{return a.name < b.name })</br>");
Print(users.sort((a,b)=>{return a.name < b.name; }));

//get user filter by age 
document.write("Only users oldest or equal than 25 : users.filter( (w) => {return w.age >= 25;} )</br>");
Print(users.filter( (w) => {return w.age >= 25;} )); 
document.write("Only users smallest or equal than 25 : users.filter( (w) => {return w.age <= 25;} )</br>");
Print(users.filter( (w) => {return w.age <= 25;} )); 

//GroupBY 
/**
* custom group by with Array.prototype.keys
**/

Array.prototype.groupBy = function(f)
{
  let groups = [];
  this.forEach( function( o )
  {
    let group =  f(o) ;
    groups[group] = groups[group] || [];
    groups[group].push( o );  
  });

  return Object.keys(groups).map( function( group )
  {
    return groups[group]; 
  })
}

document.write("Group user by age </br>");
Print(users.groupBy( (w) => {return w.age } )); 

document.write("Group user by job </br>");
Print(users.groupBy( (w) => {return w.job } )); 

document.write("Group user by job</br>");
Print(users.groupBy( (g) => {return [g.job] } ));

document.write("Group user by job and age then order by name </br>");
Print(users.sort((a,b)=>{return a.job > b.job}).groupBy( (g) => {return [g.job+g.age] } ));

document.write("Group user by job and age then order by name and filter where age < 25 and job equal AM </br>");
Print(users.sort((a,b)=>{return a.job > b.job}).filter((w)=>{ return w.age<25 || w.job == "AM" }).groupBy( (g) => {return [g.job+g.age] } ));

https://jsfiddle.net/angelfragap/0b5epjw3/29/

https://jsfiddle.net/angelfragap/0b5epjw3/29/