javascript将数组连接到另一个

我想编写一个函数来将数组连接到另一种但不同的方式:


var myNumbers = [10,20,3,4,2]

var myOperations = ['+','-','*','/']

我希望运算符位于 myNumbers 元素之间:10+20-3*4/2 = 54


天涯尽头无女友
浏览 136回答 2
2回答

www说

其他成员已经指出了一些重复的问题,他们可以帮助你。请在下面找到我为您的问题制定的解决方案。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 -希望它有帮助:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript