如何使用parseInt添加两个数字?

时间:2016-10-11 03:30:38

标签: javascript json parseint

我应该使用parseInt添加用户输入的两个数字,然后使用我的响应对象发回结果并将输出显示给用户。

例如,如果用户输入2和3,则服务器应将这些数字相加并发送回包含值5的对象。

以下是我迄今为止尝试过的内容: 的 index.js

var express = require('express');
var router = express.Router();

/* GET home page. */   

router.get('/add', function (request,response) {
    console.log('add method called');
    console.log('The parameters are: ', request.query);
    //Attempt 1
   //var parse = parseInt('#operatorA',12);
   // var parse2= parseInt('operatorB',7);

    //Attempt 2
   //var operatorA = $('#operatorA').val();
    // var operatorB = $('#operatorB').val();

    //Attempt 3
    //var a = parseInt(" ") ;
    //var b = parseInt(" ") ;
    //var x = parseInt (a + b);

    //Attempt 4
    //var x = a+b;

    //Attempt 5
    //var a = operatorA this won't work b/c operator a isn't defined here.

    //Attempt 6
    //var a = $('#operatorA').val();
    //var b = $('#operatorB').val();
    //var x = parseInt(a);
    //var y = parseInt(b);

    response.send([
        //Attempt 1
        //parse

        //Attempt 2
    //parseInt(operatorA,operatorB)

        //Attempt 3 & 4
      //  x

        //Attempt 6
        //x + y
    ]);
});
module.exports = router;

Control.js

$(document).ready(function() {
    'use strict';
    console.log('Document loaded in isit320');

    $('#read').click(read);
    $('#readJson').click(callReadJson);
    $('#add').click(add);
    }

    function add() {
        var operatorA = $('#operatorA').val();
        var operatorB = $('#operatorB').val();
        console.log('operators: ', operatorA, operatorB);
        var requestQuery = { operatorA: operatorA, operatorB: operatorB };
        $.getJSON('/add', requestQuery,function(result) {
            console.log(result);
            $('#display').html(JSON.stringify(result));
        });
    }
});

1 个答案:

答案 0 :(得分:1)

parseInt用作parseInt(string,radix),如下所示:

var a = parseInt($('#operatorA').val(), 10);
var b = parseInt($('#operatorB').val(), 10);
response.send([a+b]);