问题描述
我试图得到这个q,但是没有成功...任务是在以下条件下构建函数:
I have tried to get this q but without any success...The task is to build a function by this conditions:
// b('m') -> 'bm'
// b()()('m') -> 'boom'
// b()()()()('m') -> 'boooom'
那是我的尝试:
var b = (a) => {
var counter = 0;
var times = counter += 1;
var d = (a, o, times) => {
var o = 'o'.repeat(times);
return ('b' + o + a);
};
return d();
};
console.log(b('m'));
推荐答案
作为naomik和NinaScholz提出的另一种变体,您可以避免使用额外的可选参数,而使用 this
上下文(在ES6中)存储一个数字基元值,该值跟踪要产生多少'o'
个字符:
As another variant of what naomik and NinaScholz proposed, you could avoid the extra optional argument, and use the this
context (in ES6) to store a number primitive value that tracks how many 'o'
characters to produce:
function b(a) {
return a ? 'b' + 'o'.repeat(+this) + a : b.bind((+this||0)+1);
}
console.log(b('m'));
console.log(b()('m'));
console.log(b()()('m'));
console.log(b()()()('m'));
仅当使用(真实的)参数调用 b
时才组成字符串:该字符串是"b"
后跟许多"o"
字符(由 this
确定),最后是参数(即实际调用中的"m"
).如果未定义 this
(或在非严格模式下为全局对象),则将"o"
的计数视为 0
.当使用一个参数立即调用 b
时会发生这种情况(无链接).
The string is only composed when b
is called with a (truthy) argument: that string is a "b"
followed by a number of "o"
characters (determined by this
) and finally the argument (i.e. "m"
in the actual calls). If this
is not defined (or is the global object, in non-strict mode), the count of "o"
is considered to be 0
. This happens when b
is called immediately with an argument (no chaining).
在不带参数的情况下调用 b
时,将返回函数本身,但绑定了 this
并已通过 1
进行了增强.注意:实际上它不是函数本身,而是函数的绑定变体.
When b
is called without argument, the function itself is returned, but with a this
bound to it that has been increased with 1
. NB: so it is not actually the function itself, but a bound variant of it.
这篇关于函数中的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!