PDA

View Full Version : Javascript question



Tharnid
22 Sep 2005, 11:30 PM
I am taking a Javascript class this semester and I have a question about one of my projects. Basically what I need to do is ask a user for two numbers, display those numbers to the user, add them together, and display the total. I am trying to figure out what is wrong with my code:


<script>
// This program asks the user different questions and echoes them back to the user
// it then adds the numbers together and displays the sum



var firstNumber = "";
var secNumber = "";
var numSum = firstNumber + secNumber;

firstNumber = prompt("Enter a number please", "");
//convert firstNumber to a number
firstNumber = eval(firstNumber);

secNumber = prompt("Enter another number please", "");
//convert secNumber to a number
secNumber = eval(secNumber);

alert ("Oh. " + firstNumber + " , " + secNumber )
//convert numbersum to a number
numSum = eval(numSum);
alert (numSum);
//document.write(numSum);
//numSum = alert ( "That equals );
</script>


The prompts work and it displays the two numbers for the user, but I can't get it to display the total. I am wondering if there is something wrong with my variables?? Any help would be appreciated :)

Rambo Tribble
23 Sep 2005, 07:54 AM
First, don't use eval to convert a string to a number. In fact, avoid eval in general; it is one of the most inefficient methods in the entire JavaScript arsenal. Instead, use parseInt or parseFloat as in:


var num_str="56";
var num=parseInt(num_str);


Second, you are assigning a value to numSum when firstNumber and secNumber are null strings. That value will not automatically change just because you have assigned new values to the other variables. You must recalculate it before printing. Eval will not accomplish that, you must do the calculation itself.