Problems setting a Boolean variable

0

Hello, I am programming a web calculator with javaScript and what I want to achieve is that for example: when I add two values and I click on the minus sign, this first executes the pending sum (this is doing well), now when I enter another number and return to execute the minus sign must calculate the subtraction (what is happening is that it adds again). I am trying to control the functions with boolean variables but I see that it does not change the state of the variable. Next the code. You can help me with this because I do not see where my error is. Thanks

<body>
<table>
<tbody>
    <tr>
        <td colspan="4"><input id="display" name="display" disabled=""></td>
    </tr>

<tr>
  <td><button id="button1" value="1">1</button></td>
  <td><button id="button2" value="2">2</button></td>
  <td><button id="button3" value="3">3</button></td>
  <td><button id="addButton">+</button></td>
</tr>
<tr>
  <td><button id="button4" value="4">4</button></td>
  <td><button id="button5" value="5">5</button></td>
  <td><button id="button6" value="6">6</button></td>
  <td><button id="subtractButton">-</button></td>
</tr>
<tr>
  <td><button id="button7" value="7">7</button></td>
  <td><button id="button8" value="8">8</button></td>
  <td><button id="button9" value="9">9</button></td>
  <td><button id="multiplyButton">*</button></td>
</tr>
<tr>
  <td><button id="clearButton">C</button></td>
  <td><button id="button0" value="0">0</button></td>
  <td><button id="equalsButton">=</button></td>
  <td><button id="divideButton">÷</button></td>
</tr>
</tbody>
</table>
var nunArray = []; //arreglo que almacena los resultados
var newArray = [];
var operation = false;
var suma = false;
var restar = false;
var result = 0;
var total = 0;

//---------Funciones Auxiliares---------------------
//Convertir a entero
var convertir = function arrayANumber(array){
var num = "0";
for(var i = 0; i < array.length; i++){
    num += array[i];
}
return (parseInt(num));
}
//Funcion Suma
var sumaFuncion = function suma(){
    total += convertir(newArray);
    newArray.length = 0;
    suma = false;
    $('#display').val(total);
}
var restaFuncion = function resta(){
    total -= convertir(newArray);
    newArray.length = 0;
    restar = false;
    $('#display').val(total);
}
//----------Funciones de los Operadores------------------------
// Accion restar 
$('#subtractButton').click(function(){
    operation = true;   
    restar = true;
    if(suma){//Aqui se activa la funcion suma se previamente fue invocada
        sumaFuncion();
    }else if(newArray.length) {//Aqui resta si ya fue ingresado el segundo 
numero
        restaFuncion(); 
    }else if (nunArray.length){//Aqui se presiona la resta y se muestra el 
primer valor ingresado
         total = convertir(nunArray);
         $('#display').val(total);
    }
});
   //Accion sumar    
  $('#addButton').click(function(){
    operation = true;   
    suma = true;
    if(newArray.length){//Aqui ejecuta la funcion cuando se ingresa el 
  segundo valor
        sumaFuncion();
    }else if (nunArray.length) {//Aqui ejecuta la funcion cuando se ingresa 
  el primer valor
        total += convertir(nunArray);
         nunArray.length = 0;
         $('#display').val(total);
    }else{//Aqui carga el valor total o acumulador cuando se da click por 
  segunda vez el boton
        $('#display').val(total);
    }
  });

 //---------------Programacion de Botones Numericos-----------------------
 $('#button1').click(function(){
  //probar la variable global newArray
    if (operation == true) {
         newArray.push($('#button1').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button1').val());
        $('#display').val(nunArray.join(""));
    }
});
 $('#button2').click(function(){
    if (operation == true) {
        newArray.push($('#button2').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button2').val());
        $('#display').val(nunArray.join(""));
    }
});
 $('#button3').click(function(){    
    if (operation == true) {
        newArray.push($('#button3').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button3').val());
        $('#display').val(nunArray.join(""));
    }
});
 $('#button4').click(function(){    
    if (operation == true) {
        newArray.push($('#button4').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button4').val());
        $('#display').val(nunArray.join(""));
    }
});
 $('#button5').click(function(){    
    if (operation == true) {
        newArray.push($('#button5').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button5').val());
        $('#display').val(nunArray.join(""));
    }
});
 $('#button6').click(function(){    
    if (operation == true) {
        newArray.push($('#button6').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button6').val());
        $('#display').val(nunArray.join(""));
    }
});
 $('#button7').click(function(){    
    if (operation == true) {
        newArray.push($('#button7').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button7').val());
        $('#display').val(nunArray.join(""));
    }
});
 $('#button8').click(function(){    
    if (operation == true) {
        newArray.push($('#button8').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button8').val());
        $('#display').val(nunArray.join(""));
    }
});
 $('#button9').click(function(){    
    if (operation == true) {
        newArray.push($('#button9').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button9').val());
        $('#display').val(nunArray.join(""));
    }
});
  $('#button0').click(function(){   
    if (operation == true) {
        newArray.push($('#button0').val());
        $('#display').val(newArray.join(""));
    }else{
        nunArray.push($('#button0').val());
        $('#display').val(nunArray.join(""));
    }
});

//--------------Funcion de Los botones CLEAR e IGUAL------------------------      
$('#clearButton').click(function(){ 
    nunArray.length = 0;
    newArray.length = 0;
    operation = false;
    suma = false;
    multiplicar = false;
    dividir = false;
    restar = false;
    total = 0;
    $('#display').val("0");
});     

 //Accion igualar
 $('#equalsButton').click(function(){
    if(suma){
        sumaFuncion();
    }else if(restar){
         restaFuncion();
    } else{
        $('#display').val(total);
    }
  });
    
asked by user3821102 07.02.2018 в 23:18
source

1 answer

3

I see a lot of problems in the code.

On the one hand you have a variable and a function that share the name suma .

On the other hand, when the operation is marked in a different variable depending on the selected operation, there are moments when the variable suma and restar can be set to true .

It would be best if you take the pending operation in a single variable. In the example that I put the variable operacion can take the values 0 ( NINGUNA ), 1 ( SUMAR ) or 2 ( RESTAR ).

Neither do you need to keep two arrays for the entered values. If it is the first value and there is no selected operation, there is no more than executing the default addition operation on the current value that will be 0.

Here's how you could stay:

var newArray = [];
var NINGUNA = 0;
var SUMAR = 1;
var RESTAR = 2;
var operation = NINGUNA;
var total = 0;

//---------Funciones Auxiliares---------------------
//Convertir a entero
var convertir = function arrayANumber(array){
var num = "0";
for(var i = 0; i < array.length; i++){
    num += array[i];
}
return (parseInt(num));
}
// Ejecuta la operación pendiente si
// la hay y muestra el resultado
function ejecutarOperacion(){
  // Si no hay nuevo valor no hace nada
  if (!newArray.length){
    return;
  }
  // Ejecuta la operación pendiente
  switch(operation){
    case RESTAR:
      restaFuncion();
      break;
    default:
      sumaFuncion();
  }
  // Inicializa valores y muestra resultado
  newArray.length = 0;
  operation = NINGUNA;
  $('#display').val(total);
}
//Funcion Suma
var sumaFuncion = function suma(){
    total += convertir(newArray);
}
var restaFuncion = function resta(){
    total -= convertir(newArray);
}
//----------Funciones de los Operadores------------------------
// Accion restar 
$('#subtractButton').click(function(){
  // Ejecuta operación pendiente
  ejecutarOperacion();
  // Establece RESTAR como operación pendiente
  operation = RESTAR;
});
 //Accion sumar    
$('#addButton').click(function(){
  // Ejecuta operación pendiente
  ejecutarOperacion();
  // Establece SUMAR como operación pendiente
  operation = SUMAR;
});

//---------------Programacion de Botones Numericos-----------------------
$('#button1').click(function(){
   newArray.push($('#button1').val());
  $('#display').val(newArray.join(""));
});
$('#button2').click(function(){
  newArray.push($('#button2').val());
  $('#display').val(newArray.join(""));
});
$('#button3').click(function(){    
  newArray.push($('#button3').val());
  $('#display').val(newArray.join(""));
});
$('#button4').click(function(){    
  newArray.push($('#button4').val());
  $('#display').val(newArray.join(""));
});
$('#button5').click(function(){    
  newArray.push($('#button5').val());
  $('#display').val(newArray.join(""));
});
$('#button6').click(function(){    
  newArray.push($('#button6').val());
  $('#display').val(newArray.join(""));
});
$('#button7').click(function(){    
  newArray.push($('#button7').val());
  $('#display').val(newArray.join(""));
});
$('#button8').click(function(){    
  newArray.push($('#button8').val());
  $('#display').val(newArray.join(""));
});
$('#button9').click(function(){    
  newArray.push($('#button9').val());
  $('#display').val(newArray.join(""));
});
$('#button0').click(function(){   
  newArray.push($('#button0').val());
  $('#display').val(newArray.join(""));
});

//--------------Funcion de Los botones CLEAR e IGUAL------------------------      
$('#clearButton').click(function(){ 
    newArray.length = 0;
    operation = NINGUNA;
    total = 0;
    $('#display').val("0");
});     

 //Accion igualar
$('#equalsButton').click(function(){
  ejecutarOperacion();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
    <tr>
        <td colspan="4"><input id="display" name="display" disabled=""></td>
    </tr>

<tr>
  <td><button id="button1" value="1">1</button></td>
  <td><button id="button2" value="2">2</button></td>
  <td><button id="button3" value="3">3</button></td>
  <td><button id="addButton">+</button></td>
</tr>
<tr>
  <td><button id="button4" value="4">4</button></td>
  <td><button id="button5" value="5">5</button></td>
  <td><button id="button6" value="6">6</button></td>
  <td><button id="subtractButton">-</button></td>
</tr>
<tr>
  <td><button id="button7" value="7">7</button></td>
  <td><button id="button8" value="8">8</button></td>
  <td><button id="button9" value="9">9</button></td>
  <td><button id="multiplyButton">*</button></td>
</tr>
<tr>
  <td><button id="clearButton">C</button></td>
  <td><button id="button0" value="0">0</button></td>
  <td><button id="equalsButton">=</button></td>
  <td><button id="divideButton">÷</button></td>
</tr>
</tbody>
</table>

You could still optimize the code a lot more.

Here is an example that you can use to practice.

I have grouped the buttons using classes. To the operation buttons I have assigned a class operation and I have assigned it in value the value of the operation to execute. In this way with a single function you can control the event click of all of them.

In the same way to the numbers I assigned the class number (the value was already assigned to it) and so you can also control the functionality of click with a single function.

var newArray = [];
var NINGUNA = 0;
var SUMAR = 1;
var RESTAR = 2;
var MULTIPLICAR = 3;
var DIVIDIR = 4;
var operation = NINGUNA;
var total = 0;

//---------Funciones Auxiliares---------------------
//Convertir a entero
function convertir(array){
  return parseInt('0' + array.join(''));
}
// Ejecuta la operación pendiente si
// la hay y muestra el resultado
function ejecutarOperacion(){
  // Si no hay nuevo valor no hace nada
  if (!newArray.length){
    return;
  }
  // Ejecuta la operación pendiente
  switch(operation){
    case RESTAR:
      total -= convertir(newArray);
      break;
    case MULTIPLICAR:
      total *= convertir(newArray);
      break;
    case DIVIDIR:
      total /= convertir(newArray);
      break;
    default:
      total += convertir(newArray);
  }
  // Inicializa valores y muestra resultado
  newArray.length = 0;
  operation = NINGUNA;
  $('#display').val(total);
}
//----------Funciones de los Operadores------------------------
$('.operation').click(function(){
  // Ejecuta operación pendiente
  ejecutarOperacion();
  // Establece operación pendiente
  operation = parseInt($(this).val());
});
//---------------Programacion de Botones Numericos-----------------------
$('.number').click(function(){
  newArray.push($(this).val());
  $('#display').val(newArray.join(''));
});

//--------------Funcion CLEAR ------------------------      
$('#clearButton').click(function(){ 
    newArray.length = 0;
    operation = NINGUNA;
    total = 0;
    $('#display').val("0");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
    <tr>
        <td colspan="4"><input id="display" name="display" disabled=""></td>
    </tr>

<tr>
  <td><button id="button1" class="number" value="1">1</button></td>
  <td><button id="button2" class="number" value="2">2</button></td>
  <td><button id="button3" class="number" value="3">3</button></td>
  <td><button id="addButton" class="operation" value="1">+</button></td>
</tr>
<tr>
  <td><button id="button4" class="number" value="4">4</button></td>
  <td><button id="button5" class="number" value="5">5</button></td>
  <td><button id="button6" class="number" value="6">6</button></td>
  <td><button id="subtractButton" class="operation" value="2">-</button></td>
</tr>
<tr>
  <td><button id="button7" class="number" value="7">7</button></td>
  <td><button id="button8" class="number" value="8">8</button></td>
  <td><button id="button9" class="number" value="9">9</button></td>
  <td><button id="multiplyButton" class="operation" value="3">*</button></td>
</tr>
<tr>
  <td><button id="clearButton">C</button></td>
  <td><button id="button0" class="number" value="0">0</button></td>
  <td><button id="equalsButton" class="operation" value="0">=</button></td>
  <td><button id="divideButton" class="operation" value="4">÷</button></td>
</tr>
</tbody>
</table>
    
answered by 07.02.2018 / 23:56
source