javascript - 为什么 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代码,并尝试检查+、-、*、/、^运算符是否存在,但用户仍然可以给出多个空格,然后写入另一个变量
帮助表示赞赏
解决方案
目前没有禁用隐式乘法的选项,但是有一个(当前打开的)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));
}
推荐阅读
- database - Alter Table with AWS Aurora Cluster with large table (700GB)
- python - 如何从时间列表中获取平均时间
- node.js - 使用 Node.js 和 Angular 6 在 mongoose 中存储 PDF 文件
- c# - 单击表单的标题栏时会调用哪些函数?
- javascript - JavaScript 模块和 Web 应用程序插件
- android - 如何使用多个工具?
- angular - Angular:ERROR 错误:未找到组件工厂
- sql-server - 随着每个 ID 的参数变化,计数系列增加
- javascript - 如何在正则表达式中解析捕获的块
- c# - 为什么 Environment.TickCount 和键盘的 lastinputinfo.dwTime 是一样的?