首页 > web前端 > js教程 > 正文

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

WBOY
发布: 2023-08-24 15:53:09
转载
1099人浏览过

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

问题

我们需要编写一个 JavaScript 函数,它将数学表达式作为字符串接收,并将其结果作为数字返回。

我们需要支持以下数学运算符 -

运算符始终根据从左到右,* 和 / 必须在 + 和 - 之前计算。

示例

以下是代码 -

 实时演示

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 !== '') {
         outputQueue.push(new Number(str));
         str = '';
      }
      if (ch === '-') {
         if (ind == 0) {
            ch = 'negate';
         } else {
            let nextCh = exp[ind+1];
            let prevCh = exp[ind-1];
            if ((digits.includes(nextCh) || nextCh === '(' || nextCh === '-') &&
               (operators.includes(prevCh) || exp[ind-1] === '(')) {
                  ch = 'negate';
            }
         }
      }
      if (operations.length > 0) {
         let topOper = operations[operations.length - 1];
         while (operations.length > 0 && legend[topOper] &&
         ((legend[ch].assoc === 'left' && legend[ch].pred <= legend[topOper].pred) ||
         (legend[ch].assoc === 'right' && 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 === '(') {
      operations.push(ch);
   } else if (ch === ')') {
      if (str !== '') {
         outputQueue.push(new Number(str));
         str = '';
      }
      while (operations.length > 0 && operations[operations.length - 1] !== '(') {
         outputQueue.push(operations.pop());
      }
      if (operations.length > 0) { operations.pop(); }
   }
   ind++;
}
if (str !== '') { 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 === 'negate') {
            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中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号