计算器。无法将字母转换为点

问题描述 投票:0回答:1

我不明白为什么我的返回没有从带有字母“b”“y”和逗号“的情况下返回一个点,”我把console.log,看了一下,显示了一个点,但在某种程度上它仍然是一个点逗号和我的函数不适用于它。我需要这些符号在程序代码和视觉上都变成一个点。如果有人能解决这个问题,请写下为什么会发生这种情况,我想弄清楚。谢谢!

const displayEl = document.querySelector('.display');
const buttonEls = [...document.querySelectorAll('.button')];
const cleanBtnEl = document.querySelector('.clean-btn');
const operators = ['+', '-', '*', '/'];

const focusInput = () => displayEl.focus();
focusInput();

window.addEventListener('click', () => focusInput());

displayEl.addEventListener('keydown', (e) => {

  if (e.key === ' ') e.preventDefault();
  if (displayEl.value.includes('e') || displayEl.value === 'Error') displayEl.value = '';

  const key = e.key.toLowerCase();
  const valueStr = handlerKey(key);
  console.log(valueStr);
  // if (valueStr === '.') {
  //     displayEl.value += valueStr;
  // }

  if (!displayEl.value) {
    if (!blockFirstPoint(valueStr)) e.preventDefault();
  }

  if (!checkPointBeforeAndAfterOperator(valueStr)) e.preventDefault();

  if (valueStr === '.') {
    if (!limitPoints(valueStr)) e.preventDefault();
  }

  if (!displayEl.value) {
    if (!blockFirstOperator(valueStr)) e.preventDefault();
  }

  if (operators.includes(valueStr)) {
    if (!blockSpamOperators(valueStr)) e.preventDefault();
  }

  if (!replaceAndLimitZero(valueStr)) e.preventDefault();

  if (valueStr === 'delete') clear();

  if (valueStr === 'enter' || valueStr === '=') calc();
});

const handlerKey = (key) => {
  switch (key) {
    case 'f5':
    case 'f12':
      return key;
    case 'enter':
      return '=';
    case ',':
    case 'б':
    case 'ю':
      return '.';
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '+':
    case '-':
    case '*':
    case '/':
    case '.':
    case 'backspace':
    case 'delete':
    case 'tab':
    case 'arrowleft':
    case 'arrowright':
    case 'delete':
      return key;
    default:
      return null;
  }
};

buttonEls.forEach(button => {
  button.addEventListener('click', () => {

    if (displayEl.value.includes('e') || displayEl.value === 'Error') displayEl.value = '';

    const valueStr = button.innerText;

    if (!displayEl.value) {
      if (!blockFirstPoint(valueStr)) return;
    }

    if (!displayEl.value) {
      if (!blockFirstOperator(valueStr)) return;
    }

    if (!replaceAndLimitZero(valueStr)) return;

    if (valueStr === '=') {
      if (!calc()) return;
    }

    if (operators.includes(valueStr)) {
      if (!blockSpamOperators(valueStr)) return;
    }

    if (!checkPointBeforeAndAfterOperator(valueStr)) return;

    if (button.innerText === '.') {
      if (!limitPoints(valueStr)) return;
    }

    displayEl.value += valueStr;
  });
});

const blockFirstPoint = (valueStr) => {
  if (valueStr === '.') return false;
  return true;
};

const blockFirstOperator = (valueStr) => {
  if (operators.includes(valueStr)) return false;
  return true;
};

const replaceAndLimitZero = (valueStr) => {
  const currentValue = displayEl.value;
  const arrayNumbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

  if (currentValue === '0' && valueStr === '0') {
    return false;
  } else if (currentValue === '0' && arrayNumbers.includes(valueStr)) {
    displayEl.value = '';
    return true;
  }

  const lastOperatorIndex = Math.max(...operators.map(op => currentValue.lastIndexOf(op)));

  const afterLastOperator = currentValue.slice(lastOperatorIndex + 1);

  if (lastOperatorIndex !== -1) {
    if (afterLastOperator === '0' && valueStr === '0') {
      return false;
    } else if (afterLastOperator === '0' && arrayNumbers.includes(valueStr)) {
      displayEl.value = currentValue.slice(0, -1);
    }
  }
  return true;
};

const blockSpamOperators = (valueStr) => {
  const currentValue = displayEl.value;
  const lastChair = currentValue[currentValue.length - 1];

  if (operators.includes(lastChair)) displayEl.value = currentValue.slice(0, -1) + valueStr;

  if (operators.some(op => currentValue.includes(op))) return false;
  return true;
};

const checkPointBeforeAndAfterOperator = (valueStr) => {
  const currentValue = displayEl.value;
  let lastChar = displayEl.value[currentValue.length - 1];

  if (operators.includes(lastChar)) {
    if (valueStr === '.') return false;
    return true;
  }
  if (lastChar === '.' && operators.includes(valueStr)) return false;
  return true;
};

const limitPoints = (point) => {
  const lastOperator = operators.find(op => displayEl.value.includes(op));
  const currentOperator = lastOperator ? displayEl.value.split(lastOperator).pop() : displayEl.value;

  if (currentOperator.includes(point)) return false;
  return true;
};

const calc = () => {

  const currentValue = displayEl.value;
  const lastChar = displayEl.value[currentValue.length - 1];

  if (lastChar === '.') return false;

  const operator = operators.find(op => currentValue.includes(op));
  const [firstValueStr, secondValueStr] = currentValue.split(operator);

  const firstNumber = parseFloat(firstValueStr);
  const secondNumber = parseFloat(secondValueStr);

  let result;

  if (isNaN(secondNumber)) return;

  switch (operator) {
    case '+':
      result = firstNumber + secondNumber;
      break;
    case '-':
      result = firstNumber - secondNumber;
      if (0 > result) {
        displayEl.value = 'Error';
        return;
      }
      break;
    case '*':
      result = firstNumber * secondNumber;
      break;
    case '/':
      if (secondNumber === 0) {
        displayEl.value = 'Error';
        return;
      }
      result = firstNumber / secondNumber;
      break;
    default:
      displayEl.value = 'Error';
  }

  const res = result.toString();
  if (res.includes('e')) {
    displayEl.value = result;
    return;
  }
  displayEl.value = Math.round(result * 100_000_000) / 100_000_000;
};

cleanBtnEl.addEventListener('pointerdown', () => {
  deleteLastCharacter();
  let clearIntervalId;

  const clearTimeoutId = setTimeout(() => {
    clearIntervalId = setInterval(() => {
      deleteLastCharacter();
    }, 50);
  }, 500);

  const clearTime = () => {
    clearTimeout(clearTimeoutId);
    clearInterval(clearIntervalId);
  };

  cleanBtnEl.addEventListener('pointerup', clearTime);
  window.addEventListener('pointerup', clearTime);
});

const deleteLastCharacter = () => {
  const currentValue = displayEl.value;
  const cursorPosition = displayEl.selectionStart;

  if (cursorPosition === 0) {
    return;
  } else {
    displayEl.value = currentValue.slice(0, cursorPosition - 1) + currentValue.slice(cursorPosition);
  }
  displayEl.setSelectionRange(cursorPosition - 1, cursorPosition - 1);
};

const clear = () => displayEl.value = '';
@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap');
<link rel="icon" href="assets/calc.svg">
<!-- STYLES -->
<link rel="stylesheet" href="styles/colors.css">
<link rel="stylesheet" class="dark-mode" href="styles/styles.css">

<body class="overlay-dark dark">

  <div class="container-calculator">
    <h1 class="title">Calculator</h1>
    <div class="container-buttons">
      <input class="display" placeholder="Result" type="text" inputmode="none" onpaste="return false">
      <button class="clean-btn">C</button>
      <button class="button">1</button>
      <button class="button">2</button>
      <button class="button">3</button>
      <button class="button">+</button>
      <button class="button">4</button>
      <button class="button">5</button>
      <button class="button">6</button>
      <button class="button">-</button>
      <button class="button">7</button>
      <button class="button">8</button>
      <button class="button">9</button>
      <button class="button">*</button>
      <button class="button">/</button>
      <button class="button">0</button>
      <button class="button">.</button>
      <button class="button">=</button>
    </div>
    <div class="container-footer">
      <button class="git-hub">
                <a href="https://github.com/TopTTeDHbIu-DeJLbFuH4uk/Calculator?tab=readme-ov-file"
                   target="_blank">GitHub</a>
            </button>
      <button class="switcher-theme">Light Mode</button>
    </div>
  </div>

  <script src="scripts/switcher_theme.js"></script>
  <script src="scripts/math.js"></script>

javascript
1个回答
0
投票

使用

,
б
ю
.
替换为
displayEl.value.replace(/[бю,]/g, '.')
。 确保
handlerKey()
对于无效键返回
null
,以防止其输入。

const displayEl = document.querySelector('.display');
const buttonEls = [...document.querySelectorAll('.button')];
const cleanBtnEl = document.querySelector('.clean-btn');
const operators = ['+', '-', '*', '/'];

const focusInput = () => displayEl.focus();
focusInput();

window.addEventListener('click', () => focusInput());

displayEl.addEventListener('keydown', (e) => {
  if (e.key === ' ') e.preventDefault();
  if (displayEl.value.includes('e') || displayEl.value === 'Error') displayEl.value = '';

  const valueStr = handlerKey(e.key);
  if (!valueStr) {
    e.preventDefault();
    return;
  }

  if (!displayEl.value) {
    if (!blockFirstPoint(valueStr)) e.preventDefault();
  }

  if (!checkPointBeforeAndAfterOperator(valueStr)) e.preventDefault();

  if (valueStr === '.') {
    if (!limitPoints(valueStr)) e.preventDefault();
  }

  if (!displayEl.value) {
    if (!blockFirstOperator(valueStr)) e.preventDefault();
  }

  if (operators.includes(valueStr)) {
    if (!blockSpamOperators(valueStr)) e.preventDefault();
  }

  if (!replaceAndLimitZero(valueStr)) e.preventDefault();

  if (valueStr === 'delete') clear();

  if (valueStr === 'enter' || valueStr === '=') calc();

  // Replace any leftover commas, б, or ю with dots
  displayEl.value = displayEl.value.replace(/[бю,]/g, '.');
});

const handlerKey = (key) => {
  switch (key) {
    case 'f5':
    case 'f12':
      return key;
    case 'enter':
      return '=';
    case ',':
    case 'б':
    case 'ю':
      return '.'; // Convert these characters to dots
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '+':
    case '-':
    case '*':
    case '/':
    case '.':
    case 'backspace':
    case 'delete':
    case 'tab':
    case 'arrowleft':
    case 'arrowright':
    case 'delete':
      return key; // Valid characters
    default:
      return null; // Invalid key
  }
};

buttonEls.forEach(button => {
  button.addEventListener('click', () => {
    if (displayEl.value.includes('e') || displayEl.value === 'Error') displayEl.value = '';

    const valueStr = button.innerText;

    if (!displayEl.value) {
      if (!blockFirstPoint(valueStr)) return;
    }

    if (!displayEl.value) {
      if (!blockFirstOperator(valueStr)) return;
    }

    if (!replaceAndLimitZero(valueStr)) return;

    if (valueStr === '=') {
      if (!calc()) return;
    }

    if (operators.includes(valueStr)) {
      if (!blockSpamOperators(valueStr)) return;
    }

    if (!checkPointBeforeAndAfterOperator(valueStr)) return;

    if (valueStr === '.') {
      if (!limitPoints(valueStr)) return;
    }

    displayEl.value += valueStr;
  });
});

const blockFirstPoint = (valueStr) => {
  if (valueStr === '.') return false;
  return true;
};

const blockFirstOperator = (valueStr) => {
  if (operators.includes(valueStr)) return false;
  return true;
};

const replaceAndLimitZero = (valueStr) => {
  const currentValue = displayEl.value;
  const arrayNumbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

  if (currentValue === '0' && valueStr === '0') {
    return false;
  } else if (currentValue === '0' && arrayNumbers.includes(valueStr)) {
    displayEl.value = '';
    return true;
  }

  const lastOperatorIndex = Math.max(...operators.map(op => currentValue.lastIndexOf(op)));
  const afterLastOperator = currentValue.slice(lastOperatorIndex + 1);

  if (lastOperatorIndex !== -1) {
    if (afterLastOperator === '0' && valueStr === '0') {
      return false;
    } else if (afterLastOperator === '0' && arrayNumbers.includes(valueStr)) {
      displayEl.value = currentValue.slice(0, -1);
    }
  }
  return true;
};

const blockSpamOperators = (valueStr) => {
  const currentValue = displayEl.value;
  const lastChar = currentValue[currentValue.length - 1];

  if (operators.includes(lastChar)) displayEl.value = currentValue.slice(0, -1) + valueStr;

  if (operators.some(op => currentValue.includes(op))) return false;
  return true;
};

const checkPointBeforeAndAfterOperator = (valueStr) => {
  const currentValue = displayEl.value;
  const lastChar = displayEl.value[currentValue.length - 1];

  if (operators.includes(lastChar)) {
    if (valueStr === '.') return false;
    return true;
  }
  if (lastChar === '.' && operators.includes(valueStr)) return false;
  return true;
};

const limitPoints = (point) => {
  const lastOperator = operators.find(op => displayEl.value.includes(op));
  const currentOperator = lastOperator ? displayEl.value.split(lastOperator).pop() : displayEl.value;

  if (currentOperator.includes(point)) return false;
  return true;
};

const calc = () => {
  const currentValue = displayEl.value;
  const lastChar = displayEl.value[currentValue.length - 1];

  if (lastChar === '.') return false;

  const operator = operators.find(op => currentValue.includes(op));
  const [firstValueStr, secondValueStr] = currentValue.split(operator);

  const firstNumber = parseFloat(firstValueStr);
  const secondNumber = parseFloat(secondValueStr);

  let result;

  if (isNaN(secondNumber)) return;

  switch (operator) {
    case '+':
      result = firstNumber + secondNumber;
      break;
    case '-':
      result = firstNumber - secondNumber;
      if (result < 0) {
        displayEl.value = 'Error';
        return;
      }
      break;
    case '*':
      result = firstNumber * secondNumber;
      break;
    case '/':
      if (secondNumber === 0) {
        displayEl.value = 'Error';
        return;
      }
      result = firstNumber / secondNumber;
      break;
    default:
      displayEl.value = 'Error';
  }

  const res = result.toString();
  if (res.includes('e')) {
    displayEl.value = result;
    return;
  }
  displayEl.value = Math.round(result * 100_000_000) / 100_000_000;
};

cleanBtnEl.addEventListener('pointerdown', () => {
  deleteLastCharacter();
  let clearIntervalId;

  const clearTimeoutId = setTimeout(() => {
    clearIntervalId = setInterval(() => {
      deleteLastCharacter();
    }, 50);
  }, 500);

  const clearTime = () => {
    clearTimeout(clearTimeoutId);
    clearInterval(clearIntervalId);
  };

  cleanBtnEl.addEventListener('pointerup', clearTime);
  window.addEventListener('pointerup', clearTime);
});

const deleteLastCharacter = () => {
  const currentValue = displayEl.value;
  const cursorPosition = displayEl.selectionStart;

  if (cursorPosition === 0) {
    return;
  } else {
    displayEl.value = currentValue.slice(0, cursorPosition - 1) + currentValue.slice(cursorPosition);
  }
  displayEl.setSelectionRange(cursorPosition - 1, cursorPosition - 1);
};

const clear = () => displayEl.value = '';
@import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap");
<link rel="icon" href="assets/calc.svg" />
<!-- STYLES -->
<link rel="stylesheet" href="styles/colors.css" />
<link rel="stylesheet" class="dark-mode" href="styles/styles.css" />
<body class="overlay-dark dark">
    <div class="container-calculator">
        <h1 class="title">Calculator</h1>
        <div class="container-buttons">
            <input class="display" placeholder="Result" type="text" inputmode="none" onpaste="return false" />
            <button class="clean-btn">C</button>
            <button class="button">1</button>
            <button class="button">2</button>
            <button class="button">3</button>
            <button class="button">+</button>
            <button class="button">4</button>
            <button class="button">5</button>
            <button class="button">6</button>
            <button class="button">-</button>
            <button class="button">7</button>
            <button class="button">8</button>
            <button class="button">9</button>
            <button class="button">*</button>
            <button class="button">/</button>
            <button class="button">0</button>
            <button class="button">.</button>
            <button class="button">=</button>
        </div>
        <div class="container-footer">
            <button class="git-hub">
                <a href="https://github.com/TopTTeDHbIu-DeJLbFuH4uk/Calculator?tab=readme-ov-file" target="_blank">GitHub</a>
            </button>
            <button class="switcher-theme">Light Mode</button>
        </div>
    </div>
    <script src="scripts/switcher_theme.js"></script>
    <script src="scripts/math.js"></script>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.