javascript calculator: plus sign alternatives

元气小坏坏 提交于 2019-12-12 03:28:58

问题


As I was researching my current question this article seemed to be promising but I could not figure out for myself if it was the answer to my question. So if anyone could help my that would be terrific.

This is my Function:

function CalculateIMSUB(form) {
  var Atext = form.input_1.value;
  var Btext = form.input_2.value;
  var val = form.val.value;
  var A = eval(Atext);
  var B = eval(Btext);
  if (isNaN(A)) A = 0;
  if (isNaN(B)) B = 0;
  var answer = A - B;
  form.Answer.value = answer;
}

This is my html:

<form>
  <INPUT TYPE=TEXT name="input_1" SIZE=15>
  <INPUT TYPE=TEXT name="input_2" SIZE=10>
  <INPUT TYPE="button" VALUE="+" name="SubtractButton"
  onclick="CalculateIMSUB(this.form)">
  <INPUT TYPE=TEXT NAME="Answer" SIZE=12>
  <input type="hidden" name="val" value="" />
</form>

My question:

Can I add with "/"

For instance currently, if you were to type 10 / 5 in the input 1 text field and click calculate you would have an answer of 2 in the Answer text field. Since as we all know 10 divided by 5 equals 2. I would like to be able to type 10/5 into the input 1 text field and receive an answer of 15 which would be the equivalent to 10+5. Your help is greatly appreciated, thank you and here is my jsFiddle.


回答1:


You could also do this:

var Atext = form.first.value.replace(/\//g,"+");
var Btext = form.second.value.replace(/\//g,"+");

Which would replace all division operators behind the scenes so that your eval will process them as addition. (So you could put 5/5/5 and get 15, or what have you.)




回答2:


Here's a very simple calculator implementation with prototypes and a module, no eval needed.

var calc = (function calcModule() {
  function Calculator(operation) {
    this.op = operation;
    this._init();
  }

  Calculator.prototype = {
    _init: function() {
      this.n1 = +this.op.split(/\D/)[0];
      this.n2 = +this.op.split(/\D/)[1];
      this.result = this[this.op.match(/\D/)[0]]();
    },
    '+': function() { return this.n1 + this.n2 },
    '-': function() { return this.n1 - this.n2 },
    '*': function() { return this.n1 * this.n2 },
    '/': function() { return this.n1 / this.n2 }
  };

  return function(op) {
    return new Calculator(op);
  };
}());

You can change what the symbols do if you want to. You use it like so:

console.log(calc('20-15').result); //=> 5
console.log(calc('15/5').result); //=> 3
...

Note that it's very simple, it'll only work with two numbers, but just so you get an idea...



来源:https://stackoverflow.com/questions/14994946/javascript-calculator-plus-sign-alternatives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!