简体   繁体   中英

Beginning Javascript Chapter 2 finishing exercise 2

I'm working through Beginning Javascript but can't get past Chapter 2 finishing exercise 2. The exercise is to correct this bit of code

 <!DOCTYPE html>

<html lang="en">
<head>
    <title>Chapter 2, Finishing exercise 2</title>
</head>
<body>

    <script>
        var firstNumber = prompt("Enter the first number", "");
        var secondNumber = prompt("Enter the second number", "");
        var theTotal = firstNumber + secondNumber;

        document.write(firstNumber + " added to " + secondNumber + " equals " theTotal);

    </script>
</body>
</html>

I can get the correct total to display using alert, however when I remove the commenting it no longer works.

<!DOCTYPE html>

<html lang="en">
<head>
    <title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
    <script>
        var firstNumber = prompt("Enter the first number", "");
        var secondNumber = prompt("Enter the second number", "");


        var intFirstNumber = parseInt(firstNumber, 10);
        var intSecondNumber = parseInt(secondNumber, 10);
        var theTotal = intFirstNumber + intSecondNumber;


        alert(theTotal);
        //document.write (intFirstNumber + " added to " + intSecondNumber + " equals " theTotal);

    </script>
</body>
</html>

I can't figure out what about my document.write statement is wrong. Any hints? Additionally is there a more elegant way to achieve what I'm doing?

You need another + between the "equals" and theTotal :

document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal);

In this context, the + sign means concatenate (append) whatever comes after it to whatever comes before it.


Further Reading:

MDN documentation for string concatenation .

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