简体   繁体   English

ES6带有循环的箭头符号

[英]ES6 Arrow Notation with Loops

Consider the following bit of code: 考虑以下代码:

f=(m,c)=>{m?c()&f(--m,c):0}

(thanks to zzzzBov for this little nugget) (感谢zzzzBov的这个小块金)

which is a "for"-less loop 这是一个“无”循环

and the following: 以及以下内容:

a=b=>b+1

Given these two snippets, and the fact that: 鉴于以下两个摘要,以及以下事实:

z = 0; f(10,a(z));

which I would expect would result in z equating to 10, but instead returns in the JavaScript console the following "TypeError: c is not a function" , how would one go about altering this code to ensure that the loop goes ahead, without having to resort to a while or for loop? 我期望它将导致z等于10,但是在JavaScript控制台中返回以下"TypeError: c is not a function" ,如何更改此代码以确保循环继续进行而不必诉诸whilefor循环?

I'm asking this as a matter of education purposes... Hopefully I can get some insight into what can be done... 我问这是出于教育目的...希望我能对可以做的事情有所了解...

The function f is taking 2 arguments: m , the number to iterate, and c , the function to be called m times. 函数f接受2个参数: m (要迭代的数字)和c (要调用m次的函数)。 This means that the second argument, c should be a function. 这意味着第二个参数c应该是一个函数。 For example: 例如:

f=(m,c)=>{m?c()&f(--m,c):0}


f(15, function() {
 console.log("Hello")
})

This will iterate through the c function 15 times, calling console.log 15 times. 这将遍历c函数15次,调用console.log 15次。

Of course, to achieve what you wanted in the second bit, you could use this: 当然,要达到第二个目标,您可以使用以下代码:

z=0, f(10,()=>z++)

This would be a regular arrow function to increase z by 1 这将是一个常规的箭头函数,用于将z增大1

Take a look at the code on babel 看看babel上的代码

Hope I could help! 希望我能帮上忙!

It sounds you are looking for a folding function (like array reduce ), not a simple "looping" function that only executes side effects. 听起来您正在寻找的是折叠功能(如array reduce ),而不是仅执行副作用的简单“循环”功能。 With that current function, which desugars f(5, c) to effectively c(); c(); c(); c(); c(); 使用该当前函数,可以将f(5, c)减为有效c(); c(); c(); c(); c(); c(); c(); c(); c(); c(); you would need to do 你需要做

let z = 0;
f(10,()=>{ z = a(z) });

If however you want to make a function that repeatedly applies a function, like a(a(a(a(a(…))))) , you would need to write 但是,如果您要制作一个重复应用函数的函数,例如a(a(a(a(a(…))))) ,则需要编写

let times = (n, f, s) => n>0 ? times(n-1, f, f(s)) : s;

so that you can do 这样你就可以

let a = b=>b+2
times(5, a, 0) // 10

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

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