簡體   English   中英

React:Javascript Calculator:如何從 switch 語句返回一個函數?

[英]React: Javascript Calculator: How to return a function from a switch statement?

在用 React 構建的 Javascript 計算器中,有一個 switch 語句旨在返回一個函數。 如果 switch 語句在函數中,似乎允許它們返回。 但是,從 switch 語句返回函數時出現錯誤: TypeError: func is not a function

任何幫助將不勝感激。

索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';


class JavascriptCalculator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: 0,
      array: [],
    }
    this.display = this.display.bind(this);
    this.clear = this.clear.bind(this);
    this.calculate = this.calculate.bind(this);
  }

  calculate(){
    let regex = /[*/+‑]/;
    let text = '';
    let length = this.state.array.length;
    let operators = [];

    //console.log(this.state.array);

    // capture numbers longer than one digit by adding them to a string
    // add a comma in place of the operators so the string
    // can be split into an array.
    for (let i = 0; i < length; i++){
      if (this.state.array[i].match(/\d/)) {
        text+=this.state.array[i];
      }
      if (this.state.array[i].match(regex)){
        text+=',';
        // put the operators in their own array
        operators.push(this.state.array[i]);
      }
      if (this.state.array[i] == '='){
        break;
      }
    }

    console.log(operators);
    let numbers = text.split(',');
    console.log(numbers);
    let answer = 0;
    let func = undefined;

    // use the numbers array and the operators array
    // to calculate the answer.
    for (let i = 0; i < numbers.length; i++){

      func = returnFunc(operators.shift());
      console.log(func);
      answer = func(answer, numbers[i]);

    }

    function returnFunc(val) {
      switch (val) {
        case '+':
        return function sum(a,b) { return a+b};
        case '-':
        return function subtract(a,b) { return a-b};
        case '*':
        return function multiply(a,b) { return a*b};
        case '/':
        return function divide(a,b) {return a/b};
      }
    }
  }

  display(text){
    // if display is zero, remove the leading zero from the text.
    if(this.state.text == 0){
      this.state.text = '';
    }
    let displayed = this.state.text += text;
    this.setState({ text: displayed});

    // push the characters onto an array
    // an array is used to isolate the math operators to
    // associate them to a function
    if (text != '='){
      this.state.array.push(text);
    }

    // if text ends in equals sign, run the calculate function.
    if (text == '='){
      this.state.array.push(text);
      this.calculate();
    }
  }

  clear(id){
    this.setState({ text: id });
    this.setState({ array: [] });
    this.setState({ indices: [] });
    this.setState({ number: [] });
  }

  render() {
    return (
      <div id="javascript-calculator">
      <h1 id="title">Javascript Calculator</h1>
      <div id="display">{this.state.text}</div>
      <hr/>
      <div>
      <button id="clear" onClick={e => this.clear("0")}> clear </button>
      <button id="equals" onClick={e => this.display("=")}> = </button>
      <button id="zero" onClick={e => this.display("0")}> 0 </button>
      <button id="one" onClick={e => this.display("1")}> 1 </button>
      <button id="two" onClick={e => this.display("2")}> 2 </button>
      <button id="three" onClick={e => this.display("3")}> 3 </button>
      <button id="four" onClick={e => this.display("4")}> 4 </button>
      <button id="five" onClick={e => this.display("5")}> 5 </button>
      <button id="six" onClick={e => this.display("6")}> 6 </button>
      <button id="seven" onClick={e => this.display("7")}> 7 </button>
      <button id="eight" onClick={e => this.display("8")}> 8 </button>
      <button id="nine" onClick={e => this.display("9")}> 9 </button>
      <button id="add" onClick={e => this.display("+")}> + </button>
      <button id="subtract" onClick={e => this.display("-")}> - </button>
      <button id="multiply" onClick={e => this.display("*")}> * </button>
      <button id="divide" onClick={e => this.display("/")}> / </button>
      <button id="decimal" onClick={e => this.display(".")}> . </button>
      </div>
      </div>
    );
  }
}

ReactDOM.render(<JavascriptCalculator />, document.getElementById("app"));

索引.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Javascript Calculator</title>
  <style>
  </style>
</head>
<body>
  <main>
    <div id="app"></app>
    </main>
    </script>
  </body>
  </html>

您嘗試對輸入文本中的每個數字使用運算符。 但通常會有比運算符更多的數字,因此對於沒有關聯運算符的最后一個數字,這將失敗。

然后returnFunc函數將使用undefined調用,因為operators數組為空。 並且在這種情況下也將返回undefined而不是函數。

您從 answer = 0 開始,然后執行第一個操作。 相反,從答案作為第一個數字開始,然后用第二個數字進行第一個操作,依此類推

// initialize answer with first number
let answer = numbers[0];
let func = undefined;

// Start with second number 
for (let i = 1; i < numbers.length; i++){

  func = returnFunc(operators.shift());
  console.log(func);
  answer = func(answer, numbers[i]);
}

this.display(answer);

如果你有一個 switch 語句,有一個 default case 總是好的。 如果沒有其他方法來處理未知輸入,至少拋出一個異常,以便您可以識別使用無效輸入調用的開關。

function returnFunc(val) {
  switch (val) {
    case '+':
      // Error here because a and b are strings. 
      // Convert them to numbers first to add their values *
      return function sum(a,b) { return a+b}; 
    case '-':
      return function subtract(a,b) { return a-b};
    case '*':
      return function multiply(a,b) { return a*b};
    case '/':
      return function divide(a,b) {return a/b};
    default: // <- Use default case
      throw new Error("Called with unknown operator " + val);
  }
}

*) 請參閱如何將兩個字符串作為數字相加?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM