为什么我的计算器连接而不是执行运算


function add(a,b) {
parseInt(a); // cross checking
parseInt(b); // cross checking
let result = a+b;
getDis.textContent = result;
}
function sub(a,b) {
parseInt(a); // cross checking
parseInt(b); // cross checking
let result = a-b;
getDis.textContent = result;}
function mul(a,b) {
parseInt(a); // cross checking
parseInt(b); // cross checking
let result = a*b;
getDis.textContent = result;}
function div(a,b) {
parseInt(a); // cross checking
parseInt(b); // cross checking
let result = a/b;
getDis.textContent = result; }

function operate(operator2,a,b) {
if (operator2 == '+') { add(a,b)}
if(operator2 == '-') {sub(a,b)}
if(operator2 ==  '*') {mul(a,b)}
if(operator2 =='/') {div(a,b)}
} 


// Populating the display

let getDis = document.getElementById('display');
let NUM = document.querySelectorAll('.n'); // select all the buttons with numbers
NUM.forEach( (n) => {
n.addEventListener('click', () => {
getDis.textContent = getDis.textContent + '' + n.textContent;
})
})
// clearing the calculator
let CLEAR_ = document.getElementById('clear');
CLEAR_.addEventListener('click' , () => {
getDis.textContent = '';
})
// -----------------------------------------

// OPERATORS
let OPR = document.querySelectorAll('.operators'); // selecting all the operators except the equal operator
OPR.forEach( (SIGN) => { // for each operators in the nodelist returned by OPR.
SIGN.addEventListener('click', () => { // Upon clicking a operator save the first number(LHS operand) and flush the display.
let SAVE_L = getDis.textContent;
parseInt(SAVE_L); // parse it if its a string
getDis.textContent = '';
let SAVE_O = SIGN.textContent; // save the operator too for the operate() function
let EQUAL = document.getElementById('equal');
EQUAL.addEventListener('click' , ()=> {
let SAVE_R = getDis.textContent; // when equal is clicked, save the RHS operand and flush the display.
parseInt(SAVE_R); // parse it into a int if its a string
getDis.textContent = '';
operate(SAVE_O,SAVE_L,SAVE_R);})
})
})

// ----------______---------------------------

我正试图从odin项目中构建一个名为calculator的计算器。除了最后的结果是串联而不是实际的算术运算之外,我几乎已经完成了所有的工作。例如,1+1给出11,而不是2,依此类推。我如何解决这段代码中的问题?

parseInt(a);不修改a。相反,您需要a = parseInt(a);

一般来说,除了少数例外(例如array.prototype.sort(,许多内置函数都不会修改其参数。

最新更新