串联而不是添加

时间:2019-01-17 23:47:25

标签: javascript google-apps-script string-concatenation addition

好吧,我正尝试在Google脚本中创建一个计算器,每当我尝试将其添加到集中而不是添加时,我已经搜索了几个小时,将不胜感激,我已经查看了多个论坛帖子,但没有人回答我的问题,他们的变量已经是整数

function calculateNumber() {
     var calc = DocumentApp.getUi()
     var num1 = calc.prompt('Please Type First Number', calc.ButtonSet.OK)
     var one = num1.getResponseText();
     var num2 = calc.prompt('Please Type Operator', calc.ButtonSet.OK)  
     var two = num2.getResponseText()
     var num3 = calc.prompt('Please Type Second Number', calc.ButtonSet.OK)
     var three = num3.getResponseText()
     var n1 = eval(one)
     var n2 = eval(two)
     var sum = n1+n2
     if (two == '+') {
       calc.alert('Ans='+sum)

     }
   }

2 个答案:

答案 0 :(得分:0)

n1n2是字符串,您需要将它们转换为整数,使用parseInt(n1) + parseInt(n2);

答案 1 :(得分:0)

尝试这样的事情:

function calculateNumber() {
     var calc = DocumentApp.getUi()
     var num1 = calc.prompt('Please Type First Number', calc.ButtonSet.OK)
     var one = num1.getResponseText();
     var num2 = calc.prompt('Please Type Operator', calc.ButtonSet.OK)  
     var two = num2.getResponseText()
     var num3 = calc.prompt('Please Type Second Number', calc.ButtonSet.OK)
     var three = num3.getResponseText()
     if (two === '+') {
       var sum = Number(one)+Number(three);
       calc.alert('Ans='+sum)

     }
   }