Good afternoon, please help with checking the values ​​for this calculator. I know what can be done differently, but how exactly to check this one out.

Via do {var c = prompt("Введите действие которое вы хотели бы совершить: +, -, *, /, %");} while (c === "+" || c === "-" || c === "*" || c === "/" || c === "%") - does not work.

I apologize for such questions, but I do not want to leave without understanding.

 <!DOCTYPE html> <html> <head> <title>Калькулятор</title> <meta charset="utf-8"> </head> <body> <script type="text/javascript"> var res; function sum(a, b) { res = a + b; alert(res); } function sub(a, b) { res = a - b; alert(res); } function mul(a, b) { res = a * b; alert(res); } function div(a, b) { res = a / b; alert(res); } function rest(a, b) { res = a % b; alert(res); } do { var a; do { a = +prompt("Введите первое значение"); } while( isNaN(a) || a == ' '); var c = prompt("Введите действие которое вы хотели бы совершить: +, -, *, /, %"); var b; do { b = +prompt("Введите второе значение"); } while (isNaN(b) || b == ' '); switch (c) { case "+": { sum(a, b); } break; case "-": { sub(a, b); } break; case "*": { mul(a, b); } break; case "/": { div(a, b); } break; case "%": { rest(a, b); } break; } exit = confirm("Продолжить?"); if (exit) { document.write("Вы завершили выполнение."); } } while (exit); </script> </body> </html> 
  • "does not work" - and what does? - Igor

1 answer 1

 function checkThat(c){ var operatorsArr = {1:"+",2:"-",3:"/",4:"%"}; var i=0; do { if (c===operatorsArr[i]) { alert("correct") // do something after that // as example move to summ function return; } i++; }while(i<operatorsArr.length()); alert("you are wrong!"); return; } 

Those. if the block passes through all values ​​of the operatorsArr dictionary, then the wrong character was entered.

  • Thank you, I understand the logic. And where to open the function? - Andrew S.
  • Those. open? - alexoander
  • You wrote a function to check the value of "c", but in order for this check to work, the function must be opened in the code or is it possible that I understand something wrong? - Andrew S.
  • var c = prompt("Введите действие которое вы хотели бы совершить: +, -, *, /, %"); After this line, you can call this function to check the input from promt. Those. write checkThat(c); (having previously added the function itself to the scope, that is, at least somewhere to define it =)) - alexoander
  • by making the object keys themselves the values ​​of the operators, not the numbers, one could do without the cycle at all - Grundy