在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 教师闺蜜祝福语简短