HTML and CSS Reference
In-Depth Information
EXAMPLE 5.17
<html>
<head>
<title>The eval() Function</title>
</head>
<body bgcolor="lightblue">
<big>
<script type="text/javascript">
1
var str="5 + 4";
2
var num1 = eval(str); // results in 9
3
var num2 = eval(prompt("Give me a number ", ""));
4
alert(num1 + num2);
</script>
</big>
</body>
</html>
EXPLANATION
1
The string “5 + 4” is assigned to the variable str .
2
The eval() function evaluates the string expression “5 + 4” as a JavaScript instruc-
tion. The variable num1 is assigned 9 , the sum of 5 + 4 .
3
The eval() function evaluates the string value that is entered into the prompt dia-
log box (see Figure 5.27). The prompt() method always returns a string value. If
the value in the string is a number, eval() will convert the string to a number, re-
turn the number, and assign it to num2 .
4
The alert() method displays the sum of num1 and num2 in the browser window.
Figure 5.27 The eval() function converts the user input, a string, to a number (left)
to allow calculation (right).
5.4 Special Operators
In this chapter, we have covered the most commonly used JavaScript functions. Table
5.19 lists some of the other operators available to be discussed in later chapters when
they are applicable.
 
 
Search WWH ::




Custom Search