I'm a web developer newbie and am trying to build a calculator in React as a practice project.
In order to do this, I need the user-selected arithmetic operations ("+", "/", "-" or "X") to be carried out when the user clicks "=".
I push all characters of the buttons that the user clicks to an array, including arithmetic operators.
So for example if the user clicks "3", then "+", then "6", the state array (called "numberList") is [3, "+", 6]. The problem I'm having is with identifying the index of the arithmetic operator. I have tried various combinations of loops, if statements, and array methods. This is my latest attempt:
for (let i = 0; i < numberList.length; i++) {
switch (numberList[i]) {
case "+":
operator = "+";
operatorIndex = i;
break;
case "/":
operator = "/";
operatorIndex = i;
break;
case "-":
operator = "-";
operatorIndex = i;
break;
case "X":
operator = "X";
operatorIndex = i;
break;
default:
return "ERR";
}
}
//Find operators and their index in numberList
console.log(numberList, operator, operatorIndex);
But when I run this the "ERR" default is returned even when there is a matching arithmetic operator in the numberList array.
Why doesn't the code continue after "operator" and "operatorIndex" have been assigned the values of the operator and its index?
Thanks, David
Aucun commentaire:
Enregistrer un commentaire