2 回答
TA贡献1775条经验 获得超8个赞
其他成员已经指出了一些重复的问题,他们可以帮助你。请在下面找到我为您的问题制定的解决方案。
var numbersAndOperations = myNumbers.map((a, i) => myOperations[i] ? [a, myOperations[i]] : [a])
/* this makes a 2 levels deep array from your 2 and avoids any undefined values through a ternary operator.
If you don't know ternary operators they are a shorthand for an if condition.
[[10, "+"], [20, "-"], [3, "*"], [4, "/"], [2]] */
const myMathString = numbersAndOperations.flat(2).join(',').replace(/,/g, '')
// this turns it into a string and remove the comas: "10+20-3*4/2"
function mathEval(mathString) { // this hack evaluates your math function and immediately returns a result.
return new Function('return ' + mathString)();
}
console.log(mathEval(myMathString)); // 24. The result is actually 24 because * and / are evaluated before the + and -
希望它有帮助:)
添加回答
举报