我面临以下挑战描述:
“编写一个函数一次,接受回调作为输入并返回一个函数。当第一次调用返回的函数时,它应该调用回调并返回该输出。如果它被多次调用,而不是调用再次回调它只会返回第一次调用时的输出值”
给您的代码是:
function addByX(x) {
return function(num) {
return num + x;
};
}
var addByTwo = addByX(2);
function once(func) {
// ADD CODE HERE
}
var onceFunc = once(addByTwo);
// UNCOMMENT THESE TO TEST YOUR WORK!
console.log(onceFunc(4)); //should log 6
console.log(onceFunc(10)); //should log 6
console.log(onceFunc(9001)); //should log 6
我可以让代码返回您期望的结果(6, 12, 9003),但我无法让它继续记录 6.onceFunc 本身等于 addByTwo,其中 x 等于 2,因此可以传递任何数字into oneFunc 充当 n。我是否需要将第一个返回的 6 或 n=4 保存到变量中?
最佳答案
可能有更好的解决方案,但这就是我想出的。我尝试在代码中添加注释来解释它在做什么,但如果您有任何其他问题,请告诉我:https://jsfiddle.net/nvd9dqza/6/
function addByX(x) {
return function(num) {
return num + x;
};
}
var addByTwo = addByX(2);
function once(func) {
// a variable which is scoped to the "once" function
// this means you can't access "result" outside of the function
var result;
return function(num){
// since this function is scoped inside "once", it has access to result
// set the result to itself (if aleady called), or the value returned from func
result = result || func(num);
// return the result
return result;
}
}
var onceFunc = once(addByTwo);
// UNCOMMENT THESE TO TEST YOUR WORK!
console.log(onceFunc(4)); //should log 6
console.log(onceFunc(10)); //should log 6
console.log(onceFunc(9001)); //should log 6
关于javascript - 关闭挑战: returning same output from first call (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847101/