首页 > 解决方案 > 为什么 Math.js 在计算表达式时默认将乘法作为运算符?

问题描述

//Require module
const express = require('express');
const { evaluate, compile, parse } = require('mathjs');
// Express Initialize
const app = express();
const port = 8000;
app.listen(port, () => {
    console.log('listen port 8000');
 
})

//create api
app.get('/hello_world', (req, res) => {
    const expression = "A B A";
    console.log(expression.length);
    let response;
    const scope = {
        A: 5,
        B: 4
    }

    try {
        const parsedExp = parse(expression);
        const compiled = parsedExp.compile();
        const result = compiled.evaluate(scope);
        response = {
            "expression": parsedExp.toString(),
            "variables": parsedExp.args,
            "result": result
        }
          console.log("success");
          res.send(JSON.stringify(response));
    } catch (error) {
        console.log(error);    
        res.send(JSON.stringify(error));
    }
})

代码和计算工作正常。但默认情况下它采用乘法。有没有办法我们可以停止这种默认行为并向用户抛出错误消息,请输入您想要的运算符?

我什至通过空格分割尝试使用普通的javascript代码,并尝试检查+、-、*、/、^运算符是否存在,但用户仍然可以给出多个空格,然后写入另一个变量

帮助表示赞赏

标签: javascriptnode.jsmathmathjs

解决方案


目前没有禁用隐式乘法的选项,但是有一个(当前打开的)github问题。在该问题的评论中,有一种解决方法可以找到任何隐式乘法并在找到时抛出错误。

try {
  const parsedExp = parse(expression);
  parsedExp.traverse((node, path, parent) => {
    if (node.type === 'OperatorNode' && node.op === '*' && node['implicit']) {
      throw new Error('Invalid syntax: Implicit multiplication found');
    }
  });
  ...
} catch (error) {
  console.log(error);
  res.send(JSON.stringify(error));
}

推荐阅读