JavaScript で演算子の優先順位を考慮した数式の評価

WBOY
リリース: 2023-08-24 15:53:09
転載
1082 人が閲覧しました

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

質問

数式を文字列として受け取り、その結果を数値として返す JavaScript 関数を作成する必要があります。

次の数学演算子をサポートする必要があります -

  • 除算/(浮動小数点除算として)

  • 加算 p>

  • 減算-

  • 乗算*

##演算子は常に左から右に、* と / を計算する必要があります。前と-。

以下はコードです -

リアルタイムデモンストレーション

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));
ログイン後にコピー

出力

2
ログイン後にコピー

以上がJavaScript で演算子の優先順位を考慮した数式の評価の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!