如何在Javascript中将String更改为Int

时间:2019-04-27 11:12:41

标签: javascript node.js express body-parser

我无法在此代码中打印金额

// 1. create variable 
// 2. input number in variable [but it is a string]
// 3. error to print sum
// 2 variable      
let num = [""];      
let num22 = [""];  

//add this to num  

app.post("/addNum1", function(req, res){        
    let newNum1 = req.body.newnum1;        
    num.push(newNum1);        
    res.redirect("/var1");        
});

将此添加到num22

app.post("/addNum2", function(req, res){

    let newNum2 = req.body.newnum2;

    num22.push(newNum2);

    res.redirect("/var2");

});

将数字输入num

app.get("/var1", function(req, res){

    res.render("num1", {num: num});

});

输入编号为num22

app.get("/var2", function(req, res){

    res.render("num2", {num22: num22});

});

此页面显示sum + sum22的结果

app.get("/result",function(req,res){
    var a = parseInt("num");
    var b = parseInt("num22");
    var sum = parseInt("");
    sum = a+b;
    res.send(sum);
});

我的港口

 app.listen(3000, function(){
       console.log("We are in Endgame NOW!!!"); 
    });

描述
    当我输入2个数字时,我想打印该金额

1 个答案:

答案 0 :(得分:0)

global.num = '';
global.num22 = '';

app.post("/addNum1", function (req, res) {
    let newNum1 = req.body.newnum1;
    global.num = newNum1 ;
    res.redirect("/var1");
});

app.post("/addNum2", function (req, res) {

    let newNum2 = req.body.newnum2;

    global.num22 = newNum2;

    res.redirect("/var2");

});

app.get("/var1", function (req, res) {

    res.render("num1", { num: global.num });

});

app.get("/var2", function (req, res) {

    res.render("num2", { num22: global.num22 });

});

app.get("/result", function (req, res) {
    var a = parseInt(global.num);
    var b = parseInt(global.num22);
    var sum = a + b
    res.send(sum);
});

我们可以在nodejs中使用global变量