简体   繁体   中英

Unexpected output in javascript

I am beginner to javascript and i am getting unexpected output

here is the code

<script type="text/javascript">

        function add(a,b)
        {
            x = a+b;
            return x;
        }
        var num1 = prompt("what is your no.");
        var num2 = prompt("what is another no.")

        alert(add(num1,num2));


    </script>

it should give output as a sum of two number entered by us on prompting but it is simply concatenating the two number and popping the output

This is because the prompt function returns a String and not a Number . So what you're actually doing is to request 2 strings and then concatenate them. If you want to add the two numbers together you'll have to convert the strings to numbers:

var num1 = parseFloat(prompt("what is your no."));
var num2 = parseFloat(prompt("what is another no."));

or simpler:

var num1 = +prompt("what is your no.");
var num2 = +prompt("what is another no.");

prompt returns a string, not a number. + is used as both an addition and concatenation operator. Use parseInt to turn strings into numbers using a specified radix (number base), or parseFloat if they're meant to have a fractional part ( parseFloat works only in decimal). Eg:

var num1 = parseInt(prompt("what is your no."), 10);
//                                   radix -----^

or

var num1 = parseFloat(prompt("what is your no."));

In addition to the already provided answers: If you're using parseInt() / parseFloat(), make sure to check if the input in fact was a valid integer or float:

function promptForFloat(caption) {
    while (true) {
        var f = parseFloat(prompt(caption));
        if (isNaN(f)) {
            alert('Please insert a valid number!');
        } else {
            return f;
        }
    }
}

var num1 = promptForFloat('what is your no.');
// ...

When you prompt the user, the return value is a string, normal text.

You should convert the strings in numbers:

alert(add(parseInt(num1), parseInt(num2));

The return value of prompt is a string. So your add function performs the + operator on 2 strings, thus concatenating them. Convert your inputs to int first to have the correct result.

    function add(a,b)
    {
        x = parseInt( a ) + parseInt( b );
        return x;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM