1. Trang chủ
  2. » Công Nghệ Thông Tin

Học JavaScript qua ví dụ part 18 pptx

6 381 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 6
Dung lượng 564,36 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

When a function calls itself, execution starts at the beginning of the function, and when the function ends, the program backs up to where it was when it called the function and starts e

Trang 1

7.1.5 Recursion

Definition of recursion:

recursion: See recursion.

This definition says it all! JavaScript

sup-ports recursion So what is it? Have you

ever taken apart a Russian doll? Open up

the outside doll and there’s another

smaller duplicate doll inside it, take that

one out, and you find another, and so on, until you get down to a tiny doll at the end

Then when you put them back, you start with the last doll you opened and keep

return-ing each doll until you get back to the first one you opened A recursive function is a

function that calls itself It’s a chain of function calls to the same function The first time

it calls itself is the first level of recursion, the second time is the second level, and so on

When a function calls itself, execution starts at the beginning of the function, and when

the function ends, the program backs up to where it was when it called the function and

starts executing from that point Most important, there must be a way to stop the

recur-sion, or it will be infinite, and probably cause the program to crash

An example often used to describe recursion can be demonstrated with a function to

produce a Fibonacci sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and so on

Here is a little bit of history about how this formula was derived

In the beginning of the 13th century, an Italian mathematician, Leonardo Fibonacci,

was trying to solve the following problem presented at a mathematical competition in

Pisa: How many rabbits would be produced in a year if, beginning with a single pair of

rabbits, every month each pair reproduces a new pair of rabbits, which become

produc-tive when they are one month old, and none of them die, and so on? Fibonacci came up

Figure 7.14 The closure remembers the values of local variables.

Trang 2

with a formula, named after himself, to answer the rabbit question The sequence starts

with 0 and 1, and then produces the next number by adding the two previous numbers

together; so 0 + 1 is 1, 1 + 1 is 2, 1 + 2 is 3, 2 + 3 is 5, and so on

In Example 7.10, the Fibonacci sequence recurses 20 times and as you can see, if

these numbers represent rabbits, we have over 4,000 rabbits in a short period of time!

E X A M P L E 7 1 0

<html>

<head><title="Fibonacci Series"</title>

<script type="text/javascript">

switch(num){

case 0 :

break;

case 1:

break;

default:

break;

} }

</script>

</head>

<body>

<big>

<div align = "center">

<table border="1">

<tr>

<script type = "text/javascript">

document.write("<td>" + value + "</td>");

}

9 alert("Function called itself "+ count + " times!!");

</script>

</tr>

</table>

</div>

</big>

</body>

</html>

Trang 3

E X P L A N A T I O N

1 The variable, count, is initialized outside the function, making it global It will

keep track of the number of times the fib() function is called.

2 The fib() function introduces the concept of recursion, a function that calls itself

This function starts the initial task and in itself is not recursive When the same

task needs to be repeated, that is when fib() will call itself.

3 Each time the function is called, the value of count is incremented by 1.

4 The first two Fibonacci numbers are 0 and 1, and each remaining number is the

sum of the previous two The switch statement is used to check for the incoming

values of a number, num If num is 0, the value returned will be 0; if it is 1, the

value returned is 0 + 1 Because these cases are so simple there is no need for

re-cursion If the number is greater than 1, then the default case is entered

5 The first values in the sequence are 0 and 1 The value 1 is returned

6 This is the heart of the recursive program If the number is not 0 or 1, the default

case is entered, and the remaining number is the sum of the previous two

num-bers The function fib() is used within its own definition The result of the first

call to the fib() function is added to the result of next call to fib() , returning the

result to line 8

7 The loop iterates 20 times For each iteration, the function fib() is called, which

calls itself

8 Each time through the for loop, the function fib() is called passing the value n as

its argument (see line 6)

9 The value of the count variable increases by one every time the fib() function is

called With recursion, the function was called 35,400 times (see Figure 7.15)

Trang 4

E X A M P L E 7 1 1

<html>

<head>

<title>Recursion</title>

<script type="text/javascript">

1 function upDown(num){

2 document.write("<b><font size='+1'>Level "

+ num + "</b><br />");

5 document.write("<em>Level "+ num + "<em><br />");

} }

</script>

</head>

<body bgcolor="lightblue">

<h2>Recursion</h2>

<script type="text/javascript">

</script>

</body>

</html>

E X P L A N A T I O N

1 The first time this function is called it is passed the number 1

2 The function prints out the level number, Level 1

3 If the value of num is less than 4, the function calls itself.

4 When the function calls itself, it adds 1 to the value of num and restarts execution

at the top of the function, this time with the value of num equal to 2 Each time

the function calls itself, it creates a new copy of num for that recursion level The

other copy is on hold until this one is finished The function keeps calling itself

and printing level numbers in bold text until the if statement fails; that is, until

the value of num is not less than 4.

5 This line won’t be executed until the recursion stops—when the value of num is

4 When that happens, the current version of upDown() is finished, and we back

off to the previous called function and start execution at line 5 This process

con-tinues until all of the functions have completed execution

6 This is the first call to the upDown() function The argument is the number 1 The

output is shown in Figure 7.16

Trang 5

ptg

Trang 6

7.1.6 Functions Are Objects

For a discussion on how functions behave as objects See “Classes and User-Defined

Functions” on page 182 in Chapter 8, “Objects.”

7.2 Debugging Techniques

Now that we have covered some of the fundamental JavaScript constructs, this is a good

time to introduce some debugging techniques As your programs grow, so do your

chances to create errors Getting to know how to deal with these problems will save you

much time and frustration

7.2.1 Function Syntax

When working with functions there are some simple syntax rules to watch for:

1 Did you use parentheses after the function name?

2 Did you use opening and closing curly braces to hold the function definition?

3 Did you define the function before you called it? Try using the typeof operator

to see if a function has been defined

4 Did you give the function a unique name?

5 When you called the function is your argument list separated by commas? If

you don’t have an argument list, did you forget to include the parentheses?

6 Do the number of arguments equal to the number of parameters?

7 Is the function supposed to return a value? Did you remember to provide a

vari-able or a place in the expression to hold the returned value?

8 Did you define and call the function from within a JavaScript program?

Figure 7.17 shows function errors displayed by the JavaScript Error Console in

Firefox This is a very useful debugging tool for immediate error checking Just click the

Tools menu and go to Error Console These error messages make troubleshooting your

scripts much easier Figures 7.18 through 7.20 show errors in other browsers

Figure 7.17 Function errors in the JavaScript Error Console (Firefox).

Ngày đăng: 04/07/2014, 02:20