I am making a calculator and pushing/saving all the numbers and operators clicked to an array and a string.
I want to know which approach is the best in this case. Making a string or an array from the input OR a better approach I can't think of.
I want to compute the array or string. The string is giving wrong answers and I don't have a clue on how I can compute the array. The demo calculator is below.
$(document).ready(function(){
var inputArr = [];
var inputStr = '';
$('span').click(function(){
$('#input').append($(this).text());
//push to inputArr
inputArr.push($(this).text());
//add to inputStr
inputStr += $(this).text();
});
//Get result
$('.equals').click(function(){
$('#result').text(inputArr);
$('#result').append("<br/>" + parseInt(inputStr));
});
$('.clear').click(function(){
// clear everything
$('#input').text('');
inputArr = [];
inputStr = '';
});
});
span {
background: #bbb;
border-radius: 2px;
margin: 5px;
padding: .5em;
cursor: pointer;
}
.equals{
width: 30%;
background: #bbb;
border-radius: 2px;
margin: 15px;
padding: .5em;
cursor: pointer;
text-align: center;
font-size: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span>
<br/>
<br/>
<span>6</span> <span>7</span> <span>8</span> <span>9</span> <span>0</span>
<br/><br/>
<span>+</span><span>-</span><span>*</span><span>/</span><span class='clear'>clear</span>
<p class="equals"> = </p>
<p id="input"></p>
<p id='result'></p>
I tried using parseInt(inputStr)
but it gives wrong answers.