繁体   English   中英

如何在普通 function 中写箭头 function

[英]How to write arrow function in a normal function

是的,我看到了很多关于类似主题的建议,其中大多数都没有解决我的问题

这是一本书中的代码,我试图理解箭头 function 的工作,因为我非常习惯于正常的 function ......

谢谢你

const schools = ["Yorktown", "Washington & Liberty", "Wakefield"];
const wSchools = schools.filter(school => school[0] === "W");
console.log(wSchools);
// ["Washington & Liberty", "Wakefield"]

我已经尝试过这种方式但没有得到我想要的结果

const wSchools = schools.filter(function(school) {
school[0] === "W";
return school;
});

预先感谢您的详尽解释。

它超级简单只需改变这个

const wSchools = schools.filter(function(school) {
   school[0] === "W";
   return school;
});

至此

const wSchools = schools.filter(function(school) {
   return school[0] === "W";
});

说明:这是根据MDN的 Arrow function 的基本语法

param => expression 

也可以写成

(param) => { return expression }

您在代码正确性方面正确编写了 function,但您有一个逻辑错误。 使用数组过滤器时,您必须返回 true 或 false。

const wSchools = schools.filter(function(school) {
return school[0] === "W";
});

问题已得到解答,但 OP 要求了解箭头功能,所以现在让我们进一步了解 go:

箭头函数只是捕获当前代码块的 scope 的简单函数。 它非常有用,我绝对鼓励您深入了解这些内容。

您遇到的特定形式是简洁的形式,其中 function 的主体可以简化为单个 return 语句

拿这个常规的 function:

function(a, b) { return a === b }

它可以转换成这个箭头 function:

(a, b) => { return a === b }

但是由于我们的 function 只返回一个非常简单的测试结果,我们可以通过直接省略花括号和 return 语句来缩短它:

(a, b) => a === b

漂亮而简短,非常适合回调。

这里有一些关于箭头函数的文献,希望你能更好地理解它们并更舒服地使用它们,它会给你超能力:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM