javascript - 带有javascript的简单计算器,它的功能计算器不适用
问题描述
我是 Javascript 新手,所以这可能是一个简单的解决方法,但我无法弄清楚。我正在使用 HTML、CSS 和 Javascript 制作计算器,而我几乎只知道声明、if/else 语句、for/while 循环以及 CSS 和 HTML 的一些基本元素。
这是我用于计算器的 javascript 代码。
var firstNum, operator, previousKey, previousNum;
const calculator = document.querySelector('.calculator');
const buttons = calculator.querySelector('.calculator__buttons');
const display = document.querySelector('.calculator__display');
function calculate(n1, operator, n2) {
let result = '';
if(operator === '+'){
result = n1 + n2;
}else if(operator === '-'){
result = n1 - n2;
}else if(operator === '*'){
result = n1 * n2;
}else if(operator === '/'){
result = n1 / n2;
}
return result;
}
buttons.addEventListener('click', function (event) {
const target = event.target;
const action = target.classList[0];
const buttonContent = target.textContent;
if (target.matches('button')) {
let firstNum = 0;
if (action === 'number') {
if (display.textContent > 0 ) {
display.textContent += buttonContent //
}
else {display.textContent = buttonContent}
//display.textContent = buttonContent
console.log('number1 ' + buttonContent + ' button1');
previousKey = 'number';
}
if (action === 'operator') {
console.log('operator1 ' + buttonContent + ' button1');
operator = buttonContent;
firstNum = display.textContent
//console.log(firstNum)
return firstNum
previousKey = 'operator';
}
if (action === 'decimal') {
// console.log('deciaml1');
previousKey = 'decimal';
}
if (action === 'clear') {
display.textContent = '0'
console.log('clear1');
previousKey = 'clear';
}
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(firstNum, operator, display.textContent)
previousKey = 'calculate';
}
}
});
虽然我将上面的算术运算设置为函数 calculate(n1, operator, n2)
我的计算器//这是它的样子。
5-9 的结果为 -59。如果我能得到一些帮助,我将不胜感激。先感谢您。
解决方案
问题是您正在将字符串发送到计算函数。因此,您应该在代码中将字符串 textContent 显式转换为整数值:
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(parseInt(firstNum,10), operator, parseInt(display.textContent,10))
previousKey = 'calculate';
}
推荐阅读
- mongodb - 如何根据 pymongo 聚合中组字段值的最大值添加过滤器
- android - 在 Android 上使用 SQLite 创建表时看不到语法错误
- sql - 根据结果中的值抑制行
- angular - 无法在多选下拉Angular 6中显示数据
- arrays - Ada -- 无约束对象的队列数组导致 Storage_Error -- 如何解决?
- python - 如何将 pandas DataFrame 转换为数组表示?
- c++ - 如何禁用“不支持优化标志”的clang警告
- macos - 应用程序在 Android 设备中安装并自行卸载
- c++ - 尽管参数是 r 值引用,为什么要使用 std::move
- javascript - 不允许加载本地资源 - angular7 和电子