我如何重构我的JS函数,以确保这个console.log结构的工作?



我正在使用这种方法来解决这个问题,但仍然,我的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
}));

  • 首先,您的operation对象格式不好,有一个额外的逗号
  • 这是不必要的:
x: this.x,
y: this.y,

…因为在你的函数实参中已经有了形参。

  • "sum": (x, y),由于同样的原因,x, y参数不是必需的。
  • 使用includes()检查是否有有效的操作,使条件如下:
!['sum', 'multiply', 'subtract', 'divide'].includes(operation)
  • executeCalculator()函数没有返回任何东西,您需要返回操作,这就是您获得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
}));

最新更新