将字符串加法存储在计算器函数

时间:2018-01-28 17:37:04

标签: javascript variables operators addition

我想在JavaScript中使用计算器,所以我开始使用加法操作。

我尝试将加法运算符转换为字符串以添加到变量中,以便我可以从函数中添加值。我发现不可能有更好的方法来解决这个问题。

Codepen



var store = '';
var totalvalue;


function one() {
  store += "1";
  totalvalue = Number(store);
  console.log(totalvalue);
  document.querySelector('.exit').textContent = store;
}


function two() {
  store += "2";
  totalvalue = Number(store)
  console.log(totalvalue);
  document.querySelector('.exit').textContent = store;
}


function add()
{
  store = '+';
  totalvalue = parseInt(store);
  //THIS IS WHERE ITS NOT WORKING I CAME TO KNOW THAT I CANT STORE A OPERATOR
  console.log(totalvalue);
  document.querySelector('.exit').textContent = store;
}

function equalsto() {
  console.log(totalvalue);
  document.querySelector('.total').textContent = totalvalue;
}

<button class="addition" onclick="add()">+</button><br>
<button class="one" onclick="one()">1</button><br>
<button class="two" onclick="two()">2</button><br>
<button class="output" onclick="equalsto()">=</button>

<p class="exit"></p>
<h1 class="total">total</h1>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你做错了,在商店变量中,你应该将所有命令和数字的字符串加起来并使用eval来获得结果,而你只是用当前点击的值opreraton替换store vaiable 你首先要添加+符号来存储,然后解析它:

function add()

{

    store+ = '+';

    totalvalue = parseInt(store);


    console.log(totalvalue);
    document.querySelector('.exit').textContent = store;


}

更好的方法是设计按钮并将完整字符串中的文本转换为最终变量。要评估结果&#39; =&#39; ,你可以使用

ans=eval(string_of_variable)

&#13;
&#13;
#e {
  background-color: red;
}

button:nth-child(4n+2) {
  display: block;
}
&#13;
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>0</button>
<button>+</button>
<button>-</button>
<button>/</button>
<button>*</button>
<p id="e">= (Click to evaluate)</p>
<br>
<p id="ex"></p>
<script>
  var main = "";
  $("button").click(function() {
    main += ($(this)[0].innerText);
    $("#ex")[0].innerText = main;
  });
  $("#e").click(function() {
    alert("Answer of " + main + " is: " + eval(main));
    main = "";
  });
</script>

</html>
&#13;
&#13;
&#13;