>  기사  >  웹 프론트엔드  >  JavaScript에서 연산자 우선 순위를 고려하여 수학 표현식 평가

JavaScript에서 연산자 우선 순위를 고려하여 수학 표현식 평가

WBOY
WBOY앞으로
2023-08-24 15:53:091051검색

在 JavaScript 中考虑运算符优先级评估数学表达式

Question

수학 표현식을 문자열로 받고 그 결과를 숫자로 반환하는 JavaScript 함수를 작성해야 합니다.

다음 수학 연산자를 지원해야 합니다. -

  • 나누기 / (부동 소수점 나누기)

  • 덧셈 + p>

  • 뺄셈 -

  • 곱셈*

연산자는 항상 기반으로 왼쪽 오른쪽에서는 * 및 /가 + 및 -보다 먼저 평가되어야 합니다.

Example

코드는 다음과 같습니다. -

실시간 데모

const exp = '6 - 4';
const findResult = (exp = '') => {
   const digits = '0123456789.';
   const operators = ['+', '-', '*', '/', 'negate'];
   const legend = {
      '+': { pred: 2, func: (a, b) => { return a + b; }, assoc: "left" },
      '-'&: { pred: 2, func: (a, b) => { return a - b; }, assoc: "left" },
      '*': { pred: 3, func: (a, b) => { return a * b; }, assoc: "left" },
      '/': { pred: 3, func: (a, b) => {
      if (b != 0) { return a / b; } else { return 0; }
   }
   }, assoc: "left",
   'negate': { pred: 4, func: (a) => { return -1 * a; }, assoc: "right" }
};
exp = exp.replace(/\s/g, '');
let operations = [];
let outputQueue = [];
let ind = 0;
let str = '';
while (ind < exp.length) {
   let ch = exp[ind];
   if (operators.includes(ch)) {
      if (str !== &#39;&#39;) {
         outputQueue.push(new Number(str));
         str = &#39;&#39;;
      }
      if (ch === &#39;-&#39;) {
         if (ind == 0) {
            ch = &#39;negate&#39;;
         } else {
            let nextCh = exp[ind+1];
            let prevCh = exp[ind-1];
            if ((digits.includes(nextCh) || nextCh === &#39;(&#39; || nextCh === &#39;-&#39;) &&
               (operators.includes(prevCh) || exp[ind-1] === &#39;(&#39;)) {
                  ch = &#39;negate&#39;;
            }
         }
      }
      if (operations.length > 0) {
         let topOper = operations[operations.length - 1];
         while (operations.length > 0 && legend[topOper] &&
         ((legend[ch].assoc === &#39;left&#39; && legend[ch].pred <= legend[topOper].pred) ||
         (legend[ch].assoc === &#39;right&#39; && legend[ch].pred < legend[topOper].pred))) {
            outputQueue.push(operations.pop());
            topOper = operations[operations.length - 1];
         }
      }
      operations.push(ch);
   } else if (digits.includes(ch)) {
      str += ch
   } else if (ch === &#39;(&#39;) {
      operations.push(ch);
   } else if (ch === &#39;)&#39;) {
      if (str !== &#39;&#39;) {
         outputQueue.push(new Number(str));
         str = &#39;&#39;;
      }
      while (operations.length > 0 && operations[operations.length - 1] !== &#39;(&#39;) {
         outputQueue.push(operations.pop());
      }
      if (operations.length > 0) { operations.pop(); }
   }
   ind++;
}
if (str !== &#39;&#39;) { outputQueue.push(new Number(str)); }
   outputQueue = outputQueue.concat(operations.reverse())
   let res = [];
   while (outputQueue.length > 0) {
      let ch = outputQueue.shift();
      if (operators.includes(ch)) {
         let num1, num2, subResult;
         if (ch === &#39;negate&#39;) {
            res.push(legend[ch].func(res.pop()));
         } else {
            let [num2, num1] = [res.pop(), res.pop()];
            res.push(legend[ch].func(num1, num2));
         }
      } else {
         res.push(ch);
      }
   }
   return res.pop().valueOf();
};
console.log(findResult(exp));

Output

2

위 내용은 JavaScript에서 연산자 우선 순위를 고려하여 수학 표현식 평가의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제