javascript - 如何在一次()函数中删除未定义的返回(不更改以前的函数)
问题描述
我有两个代码片段,它们在 add(y) 函数的定义上有所不同。一个使用console.log()(原始版本),一个修改为使用return。第二种方法可以让我的提示通过,即...
编写一个函数,接受回调作为输入并返回一个函数。第一次调用返回的函数时,它应该调用回调并返回该输出。如果再次调用它,它不会再次调用回调,而是简单地返回第一次调用时的输出值。
如何在不修改 add(y) 的情况下重构第一个代码以实现在第二个代码中返回的所需结果?
//Challenge 4
function addByX(x) {
function add(y) {
console.log(y + x);
}
return add;
}
var addByTwo = addByX(2);
// now call addByTwo with an input of 1
//addByTwo(1);
// now call addByTwo with an input of 2
//addByTwo(5);
//Challenge 5
function once(func) {
var answer;
function inner(x) {
if (!answer) {
answer = func(x);
return answer;
} else {
return answer;
}
}
return inner;
}
var onceFunc = once(addByTwo);
// UNCOMMENT THESE TO TEST YOUR WORK!
console.log(onceFunc(5)); //should log 7
console.log(onceFunc(10)); //should log 7
console.log(onceFunc(9001)); //should log 7
第二个代码(作品)
//Challenge 4
function addByX(x) {
function add(y) {
return y + x;
}
return add;
}
var addByTwo = addByX(2);
// now call addByTwo with an input of 1
//addByTwo(1);
// now call addByTwo with an input of 2
//addByTwo(5);
//Challenge 5
function once(func) {
var answer;
function inner(x) {
if (!answer) {
answer = func(x);
return answer;
} else {
return answer;
}
}
return inner;
}
var onceFunc = once(addByTwo);
// UNCOMMENT THESE TO TEST YOUR WORK!
console.log(onceFunc(5)); //should log 7
console.log(onceFunc(10)); //should log 7
console.log(onceFunc(9001)); //should log 7
解决方案
我们可以使用闭包来捕获函数何时被调用一次。called
当is的标志true
已经被调用时,在这种情况下,它返回value
函数第一次运行时设置的那个。或者,如果这是第一次运行该函数,我们设置callback
TOtrue
并设置value
为cb
使用参数调用的函数str
。无论哪种情况,我们都会返回这个值。
function string_callback(cb) {
let called = false,
value;
return function(str) {
if (called) return value;
called = true;
value = cb(str);
return value;
}
}
let my_func = string_callback((input) => input.toUpperCase());
my_func("hihihih");
console.log(my_func("banana"));
console.log(my_func("banana"));
console.log(my_func("banana"));
Write a function once that accepts a callback as input and returns a function. When the returned function is called the first time, it should call the callback and return that output. If it is called any additional times, instead of calling the callback
again it will simply return the output value from the first time it was called.
推荐阅读
- java - 带有 .forEach 和 .add 的 Java ForkJoinPool
- quarkus - Quarkus 有 Spring AOP 模拟吗?
- javascript - 添加一个按钮以使用 Highchart 在图形和表格之间切换
- reactjs - React Router - 嵌套路由似乎不起作用
- fortran - 关于 Fortran 中 SGESV 语法的问题
- php - composer 需要 symfony/assets 安装
- asp.net - 无法在 MySql DbContext 的 dotnet ef 迁移中创建对象错误,但适用于 Sqlite DbContext
- javascript - 如何使用 JavaScript 在标准 HTML 文本中显示插入符号?
- c# - 解决方案 repo 结构 -VS Azure 函数
- android - MissingPluginException(未找到通道 video_thumbnail 上的方法文件的实现)