AddEventListener 只运行一次并且只会将 1 个值发送到数组中

AddEventListener runs only once and will only send 1 value into the array

我正在构建一个计算器作为我的第一个 JS 项目(我们被严格要求不要使用 eval)。

我设置了一个空数组,这样每次单击一个按钮(带有一个数字值)时,该值将使用 .push() 放入数组中。这样我就可以将所有数值连接在一起。因为如果用户按下按钮 1,然后按下按钮 6,我将得到的数字是 16。

问题是,事件侦听器只会 运行 一次,并且只会在字符串中添加 1 个数字。 getValue 函数将首先检查变量是否为 empty/undefined。如果是这样,它将把每个按钮的数值压入数组...

let number1;
let number2;
let operator;

const getValues = () => {
  const numValue = document.querySelectorAll('.number');

  numValue.forEach(number => {
    number.addEventListener('click', () => {
      if (typeof number1 === 'undefined') {
        number1 = [];
        number1.push(number.value)
        display.innerHTML += ` ${number.value}  `;
        console.log(number1);
      } else if (typeof number1 !== 'undefined' && typeof number2 === 'undefined') {
        number2 = number.value;
        display.innerHTML += ` ${number.value}  `;
        console.log(number2)
      }
    })
  });

  const getOperators = () => {
    const operatorValue = document.querySelectorAll('.operator');

    operatorValue.forEach(operatorBtn => {
      operatorBtn.addEventListener('click', () => {
        if (typeof operator === 'undefined') {
          operator = operatorBtn.value;
          display.innerHTML += `  <b>${operatorBtn.value}</b>  `;
          console.log(operator);
        }
      })
    })
  }

  getOperators();

  const calculation = () => {
    const equal = document.querySelector('.equal')

    equal.addEventListener('click', () => {
      if (typeof number1 !== 'undefined' && typeof number2 !== 'undefined' && operator.includes('+')) {
        console.log(+number1 + +number2)
        let result = +number1 + +number2;
        display.innerHTML += ` = ${result} `;
        return result;
      } else if (typeof number1 !== 'undefined' && typeof number2 !== 'undefined' && operator.includes('-')) {
        console.log(+number1 - +number2)
        let result = +number1 - +number2;
        display.innerHTML += ` = ${result} `;
      } else if (typeof number1 !== 'undefined' && typeof number2 !== 'undefined' && operator.includes('x')) {
        console.log(+number1 * +number2)
        let result = +number1 * +number2;
        display.innerHTML += ` = ${result} `;
      } else if (typeof number1 !== 'undefined' && typeof number2 !== 'undefined' && operator.includes('/')) {
        let result = +number1 / +number2;
        display.innerHTML += ` = ${result} `;
        console.log(+number1 / +number2)
      }
    })
  }
  calculation()
}

getValues();
<main class="calculator">

  <div id="display"></div>

  <button class="button operator" value="+">+</button>
  <button class="button operator" value="-">-</button>
  <button class="button operator" value="x">x</button>
  <button class="button operator" value="/">/</button>

  <button class="button number" value="7">7</button>
  <button class="button number" value="8">8</button>
  <button class="button number" value="9">9</button>
  <button class="button number" value="4">4</button>
  <button class="button number" value="5">5</button>
  <button class="button number" value="6">6</button>
  <button class="button number" value="1">1</button>
  <button class="button number" value="2">2</button>
  <button class="button number" value="3">3</button>

  <button class="button number" value="0">0</button>
  <button class="button point" value=".">.</button>

  <input type="reset" class="button" id="reset">

  <button class="button equal" value="=">=</button>

</main>

我进行了一些更改以使您的代码正常工作。这仍然需要大量重构,但这是一个好的开始,因为您是从这里开始的。

我重构的东西有内联注释。

您可以进行的其他重构是:

  1. 使重置功能正常工作
  2. 为操作创建一个高阶函数。在 mdn 上阅读更多相关信息。
  3. 事件委托,这样您就不会在每个元素上附加事件,而只是在父元素上。也可以在 mdn 上阅读相关内容。

let number1 = []; // Initialize the array
let number2 = []; // Initialize the array
// Keep a boolean value to know which number you are filling. You will push values into number array based on this value. It will be set to false once you press an operator.
let isFillingNumber1 = true; 
let operator;

const getValues = () => {
  const numValue = document.querySelectorAll('.number');

  numValue.forEach(number => {
    number.addEventListener('click', () => {
      if (isFillingNumber1) { // Note the modified if/else conditions
        number1.push(number.value)
        display.innerHTML += ` ${number.value}  `;
        console.log(number1);
      } else {
        number2.push(number.value) // pushing value in number2 as well
        display.innerHTML += ` ${number.value}  `;
        console.log(number2)
      }
    })
  });

  const getOperators = () => {
    const operatorValue = document.querySelectorAll('.operator');

    operatorValue.forEach(operatorBtn => {
      operatorBtn.addEventListener('click', () => {
        if (typeof operator === 'undefined') {
          operator = operatorBtn.value;
          display.innerHTML += `  <b>${operatorBtn.value}</b>  `;
          isFillingNumber1 = false; // Making isFillingNumber1 false so as to enter in number2
          console.log(operator);
        }
      })
    })
  }

  getOperators();

  const calculation = () => {
    const equal = document.querySelector('.equal')

    equal.addEventListener('click', () => {
      number1 = number1.join(""); // Joining the array to make a string.
      number2 = number2.join("");
      if (typeof number1 !== 'undefined' && typeof number2 !== 'undefined' && operator.includes('+')) {
        console.log(+number1 + +number2)
        let result = +number1 + +number2;
        display.innerHTML += ` = ${result} `;
        return result;
      } else if (typeof number1 !== 'undefined' && typeof number2 !== 'undefined' && operator.includes('-')) {
        console.log(+number1 - +number2)
        let result = +number1 - +number2;
        display.innerHTML += ` = ${result} `;
      } else if (typeof number1 !== 'undefined' && typeof number2 !== 'undefined' && operator.includes('x')) {
        console.log(+number1 * +number2)
        let result = +number1 * +number2;
        display.innerHTML += ` = ${result} `;
      } else if (typeof number1 !== 'undefined' && typeof number2 !== 'undefined' && operator.includes('/')) {
        let result = +number1 / +number2;
        display.innerHTML += ` = ${result} `;
        console.log(+number1 / +number2)
      }
    })
  }
  calculation()
}

getValues();
<main class="calculator">

  <div id="display"></div>

  <button class="button operator" value="+">+</button>
  <button class="button operator" value="-">-</button>
  <button class="button operator" value="x">x</button>
  <button class="button operator" value="/">/</button>

  <button class="button number" value="7">7</button>
  <button class="button number" value="8">8</button>
  <button class="button number" value="9">9</button>
  <button class="button number" value="4">4</button>
  <button class="button number" value="5">5</button>
  <button class="button number" value="6">6</button>
  <button class="button number" value="1">1</button>
  <button class="button number" value="2">2</button>
  <button class="button number" value="3">3</button>

  <button class="button number" value="0">0</button>
  <button class="button point" value=".">.</button>

  <input type="reset" class="button" id="reset">

  <button class="button equal" value="=">=</button>

</main>