问题我们需要编写一个 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 !== '') { 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 中考虑运算符优先级评估数学表达式的详细内容。