第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

javascript將數(shù)組連接到另一個

javascript將數(shù)組連接到另一個

天涯盡頭無女友 2021-10-21 10:39:09
我想編寫一個函數(shù)來將數(shù)組連接到另一種但不同的方式:var myNumbers = [10,20,3,4,2]var myOperations = ['+','-','*','/']我希望運算符位于 myNumbers 元素之間:10+20-3*4/2 = 54
查看完整描述

2 回答

?
www說

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 -

希望它有幫助:)


查看完整回答
反對 回復 2021-10-21
  • 2 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號