簡體   English   中英

Js初學者計算器。 如果第一個字符串是運算符,如何使第一個字符串為空

[英]Js beginner calculator. How to make the first string empty in case it's an operator

有效,但允許第一個輸入是運算符(+、-、*、/、=)。 如何使第一個輸入僅為數字?

const buttons = document.querySelectorAll('button');
const display = document.querySelector('.display');

添加了一個變量來區分運營商

const operator = ['+', '-', '*', '/'];
buttons.forEach(function(button) {
  button.addEventListener('click', calculate);
});

function calculate(event) {
const clickedButtonValue = event.target.value;

試過了,沒有效果

if (display.value[0] = operator) {
  display.value = '';
}
else if (clickedButtonValue === '=' && display.value !== '') {
  display.value = eval(display.value)
} else if (clickedButtonValue === 'C') {
  display.value = ''
} else {
  display.value += clickedButtonValue;
}


}

if (display.value[0] === operator) { //changed your = operator to ===
  display.value = '';
}

這應該有效,您的問題是您將 display.value[0] 分配給 operator 而不是比較它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM