簡體   English   中英

我如何重構我的 JS function 以確保此 console.log 結構有效?

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

我正在使用這種方法來解決這個問題,但我的 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 object 格式錯誤,多了一個逗號
  • 這是不必要的:
x: this.x,
y: this.y,

...因為您的 function arguments 中已經有了參數。

  • "sum": (x, y) ,出於同樣的原因,x, y 參數不是必需的。
  • 使用includes()檢查是否存在有效操作,使條件如下:
!['sum', 'multiply', 'subtract', 'divide'].includes(operation)
  • 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