[英]How to write arrow function in a normal function
Yes i saw a lot of suggestions about similar topic and most of them didn't solve my question是的,我看到了很多关于类似主题的建议,其中大多数都没有解决我的问题
here is a code from a book am trying to understand the work of the arrow function as am very used to the normal function... how can i write the below code with a normal function..这是一本书中的代码,我试图理解箭头 function 的工作,因为我非常习惯于正常的 function ......
thank you谢谢你
const schools = ["Yorktown", "Washington & Liberty", "Wakefield"];
const wSchools = schools.filter(school => school[0] === "W");
console.log(wSchools);
// ["Washington & Liberty", "Wakefield"]
i have tried in this way but not getting the result i want我已经尝试过这种方式但没有得到我想要的结果
const wSchools = schools.filter(function(school) {
school[0] === "W";
return school;
});
thank you in advance for a thorough explanation.预先感谢您的详尽解释。
Its super simple just change this它超级简单只需改变这个
const wSchools = schools.filter(function(school) {
school[0] === "W";
return school;
});
To This至此
const wSchools = schools.filter(function(school) {
return school[0] === "W";
});
Explanation: This is the basic syntax of Arrow function according to MDN说明:这是根据MDN的 Arrow function 的基本语法
param => expression
which can also be written as也可以写成
(param) => { return expression }
You wrote the function correctly in terms of code correctness, but you have a logical error.您在代码正确性方面正确编写了 function,但您有一个逻辑错误。 You have to return a true or false when using an array filter.
使用数组过滤器时,您必须返回 true 或 false。
const wSchools = schools.filter(function(school) {
return school[0] === "W";
});
Question has been answered, but the OP asked for understanding arrow functions, so let's go further now:问题已得到解答,但 OP 要求了解箭头功能,所以现在让我们进一步了解 go:
Arrow functions are simply functions that capture the scope of the current code block.箭头函数只是捕获当前代码块的 scope 的简单函数。 It's super useful and I definitely encourage you to dig deeper in your understanding of these.
它非常有用,我绝对鼓励您深入了解这些内容。
The particular form you encountered is the concise form where the body of the function can be reduced to a single return statement .您遇到的特定形式是简洁的形式,其中 function 的主体可以简化为单个 return 语句。
Take this regular function:拿这个常规的 function:
function(a, b) { return a === b }
It could be converted to this arrow function:它可以转换成这个箭头 function:
(a, b) => { return a === b }
But since our function only returns the result of a very simple test, we can make it shorter by straight out omitting both the curly braces and the return statement:但是由于我们的 function 只返回一个非常简单的测试结果,我们可以通过直接省略花括号和 return 语句来缩短它:
(a, b) => a === b
Nice and short, perfect for callbacks.漂亮而简短,非常适合回调。
Here is some literature about arrow functions , hope you'll understand them better and get more comfortable using them, it will give you super powers:)这里有一些关于箭头函数的文献,希望你能更好地理解它们并更舒服地使用它们,它会给你超能力:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.