Heim > Web-Frontend > js-Tutorial > Hauptteil

Auswerten mathematischer Ausdrücke unter Berücksichtigung der Operatorpriorität in JavaScript

WBOY
Freigeben: 2023-08-24 15:53:09
nach vorne
1083 Leute haben es durchsucht

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

Frage

Wir müssen eine JavaScript-Funktion schreiben, die einen mathematischen Ausdruck als Zeichenfolge empfängt und ihr Ergebnis als Zahl zurückgibt.

Wir müssen die folgenden mathematischen Operatoren unterstützen –

  • Division / (als Gleitkommadivision)

  • Addition + p>

  • Subtraktion –

  • Multiplikation*

Operatoren basieren immer darauf left Nach rechts müssen * und / vor + und - ausgewertet werden.

Beispiel

Hier ist der Code -

Echtzeitdemonstration

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));
Nach dem Login kopieren

Ausgabe

2
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonAuswerten mathematischer Ausdrücke unter Berücksichtigung der Operatorpriorität in JavaScript. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:tutorialspoint.com
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!