尝试使用函数在 javascript 中添加三个数字,但它没有添加它们,而是将它们写为一个数字

Trying to add three numbers in javascript using functions but its not adding them instead it just writes them as one number

尝试使用函数在 javascript 中添加三个数字,但它没有添加它们,而是将它们写为一个数字

function numinput(a,b,c,res){
a = prompt("Enter first number");
    b = prompt("Enter second number");
    c =  prompt("Enter third number");

    res = a + b + c ;
    alert (res);
}  

numinput();

使用

将值转换为数字

parseInt

。这是一个可行的解决方案。

function numinput(a,b,c,res){
        a = parseInt(prompt("Enter first number"), 10);
        b = parseInt(prompt("Enter second number"), 10);
        c = parseInt(prompt("Enter third number"), 10);

        res = a + b + c ;
        alert (res);
    }

    numinput();

每个用户条目是 typeof string,它被连接成一个整体 string。如果要将每个元素添加为 Math 操作,请将条目解析为数字,在变量前使用 + 符号或使用 parseInt 函数对其进行解析。

function numinput(a, b, c, res) {
  a = prompt("Enter first number");
  b = prompt("Enter second number");
  c = prompt("Enter third number");

  res = +a + +b + +c;
  alert(res);
}

numinput();

您需要将每个值(字符串)转换为具有一元 + 的数字。

然后我建议将变量声明移到函数中,而不是函数参数内部,因为您不需要以这种方式使用它们,而是在函数内部赋值。

function numinput() {
    var a = +prompt("Enter first number"),
        b = +prompt("Enter second number"),
        c = +prompt("Enter third number"),
        res = a + b + c;
      
    alert(res);
}

numinput();

promptreturns一个string。您需要先将字符串转换为数字,否则您将连接字符串:'5' + '7' === '57'

以下是实现此目的的一些方法:

1 - 使用 Number

Number('5');

2 - 使用 parseInt or parseFloat

parseInt('20', 10);
parseFloat('5.5');

3 - 一元 + 运算符如其他答案所述

+'5'

工作演示:

function numinput() {
    var a = prompt("Enter first number"),
        b = prompt("Enter second number"),
        c = prompt("Enter third number"),
        res = Number(a) + Number(b) + Number(c);
      
    alert(res);
}

numinput();