在JavaScript中将字符串评估为数学表达式
我们需要编写一个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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短