首页 > 解决方案 > 如何在一次()函数中删除未定义的返回(不更改以前的函数)

问题描述

我有两个代码片段,它们在 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

标签: javascriptcallbackclosures

解决方案


我们可以使用闭包来捕获函数何时被调用一次。called当is的标志true已经被调用时,在这种情况下,它返回value函数第一次运行时设置的那个。或者,如果这是第一次运行该函数,我们设置callbackTOtrue并设置valuecb使用参数调用的函数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.


推荐阅读