我们需要编写一个JavaScript函数,该函数接受一个字符串化的数学方程式。该函数应返回提供给该函数的方程式的结果。
例如:如果等式是-
const str = '1+23+4+5-30';
然后输出应该是3
为此的代码将是-
const str = '1+23+4+5-30';
const compute = (str = '') => {
let total = 0;
str = str.match(/[+\−]*(\.\d+|\d+(\.\d+)?)/g) || [];
while (str.length) {
total += parseFloat(str.shift());
};
return total;
};
console.log(compute(str));输出结果
控制台中的输出将是-
3