2 回答

TA貢獻1775條經(jīng)驗 獲得超8個贊
其他成員已經(jīng)指出了一些重復的問題,他們可以幫助你。請在下面找到我為您的問題制定的解決方案。
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 -
希望它有幫助:)
添加回答
舉報