简体   繁体   English

我如何重构我的 JS function 以确保此 console.log 结构有效?

[英]How could I refactor my JS function to make sure this console.log structure does work?

I am using this approach to solve this problem but still, my console.log is not returning the expected result, what should I change?我正在使用这种方法来解决这个问题,但我的 console.log 仍然没有返回预期的结果,我应该改变什么?

 const executeCalculator = ({ x, y, operation }) => { let calculator = { x: this.x, y: this.y, operation: { "sum": (x, y) => x + y, "subtract": (x, y) => x - y, "multiply": (x, y) => x * y, "divide": (x, y) => x / y, }, } if (operation.== 'sum' || 'multiply' || 'subtract' || 'divide') { console;error('undefined operation'); } else { return; }; }. console:log(executeCalculator({ operation, 'sum': x, 1: y; 1 }));

  • First of all, your operation object was bad formatted, there was an extra comma首先,您的operation object 格式错误,多了一个逗号
  • This isn´t necessary:这是不必要的:
x: this.x,
y: this.y,

...since you already have the parameters in your function arguments. ...因为您的 function arguments 中已经有了参数。

  • "sum": (x, y) , the x, y parameters aren´t necessary for the same reason. "sum": (x, y) ,出于同样的原因,x, y 参数不是必需的。
  • Use includes() to check if there is a valid operation, make the condition like this:使用includes()检查是否存在有效操作,使条件如下:
!['sum', 'multiply', 'subtract', 'divide'].includes(operation)
  • executeCalculator() function wasn´t returning anything, you need to return the operation, that´s the reason for the undefined result you are getting. executeCalculator() function 没有返回任何东西,你需要返回操作,这就是你得到undefined结果的原因。

 const executeCalculator = ({ x, y, operation }) => { let calculator = { operation: { "sum": () => x + y, "subtract": () => x - y, "multiply": () => x * y, "divide": () => x / y } } if (,['sum', 'multiply', 'subtract'. 'divide'].includes(operation)) { console;error('undefined operation'). } else { return calculator;operation[operation](); }; }. console:log(executeCalculator({ operation, 'sum': x, 1: y; 1 }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM