【问题标题】:JavaScript: Create Function That Returns Function That Returns Either Value or Object Based on Input ParamJavaScript:创建返回函数的函数,该函数根据输入参数返回值或对象
【发布时间】:2019-10-27 07:43:07
【问题描述】:

我想:

创建一个函数 saveOutput,它接受一个函数(将接受一个参数)和一个字符串(将充当密码)。然后 saveOutput 将返回一个行为与传入函数完全相同的函数,除非密码字符串作为参数传入。发生这种情况时,返回的函数将返回一个对象,其中所有先前传入的参数作为键,相应的输出作为值

我尝试了以下代码:

const saveOutput = (inputFunc, str) => {

  let newObj = {}; 

  return function (value) {

    if (value === str){

      return newObj[value] = inputFunc(value)
    }
    // return a function that behaves exactly like the passed-in function
    else {
      return inputFunc(value)
    }
  }
}

// Uncomment these to check your work!
const multiplyBy2 = function(num) { return num * 2; };

const multBy2AndLog = saveOutput(multiplyBy2, 'boo');

console.log(multBy2AndLog(2)); // should log: 4
console.log(multBy2AndLog(9)); // should log: 18
console.log(multBy2AndLog('boo')); // should log: { 2: 4, 9: 18 }

我的代码返回:

console.log(multBy2AndLog(2)); // returns 4
    console.log(multBy2AndLog(9)); // returns 18
    console.log(multBy2AndLog('boo')); // returns NaN

为什么我的第三个也是最后一个 console.log 在它应该返回时返回 NaN:

{ 2: 4, 9: 18 }

【问题讨论】:

  • 因为它返回赋值的结果,即boo * 2,即NaN
  • 第一个条件仅在最后一次调用时才被调用,因此此时 newObj 中没有存储任何值。

标签: javascript function object callback return


【解决方案1】:

您必须将newObj 赋值移动到else 子句并在value === str 时返回newObj

if (value === str){     
   return newObj;
}
// return a function that behaves exactly like the passed-in function
else {
   newObj[value] = inputFunc(value);
   return inputFunc(value);
}

实例:

const saveOutput = (inputFunc, str) => {

  let newObj = {}; 

  return function (value) {

    if (value === str){     
      return newObj;
    }
    // return a function that behaves exactly like the passed-in function
    else {
      newObj[value] = inputFunc(value);
      return inputFunc(value)
    }
  }
}

// Uncomment these to check your work!
const multiplyBy2 = function(num) { return num * 2; };

const multBy2AndLog = saveOutput(multiplyBy2, 'boo');

console.log(multBy2AndLog(2)); // should log: 4
console.log(multBy2AndLog(9)); // should log: 18
console.log(multBy2AndLog('boo')); // should log: { 2: 4, 9: 18 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-18
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    相关资源
    最近更新 更多