js中遞迴函式的使用介紹

來源:互聯網
上載者:User

下面我們就做一個10以內的階乘試試看吧:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>js中遞迴函式的使用</title> </head> <body> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行] 


遞迴函式的調用就說這麼多了

js遞迴函式調用自身時的保險方式。
來自js進階程式設計
一個典型階乘遞迴函式:
複製代碼 代碼如下:
function fact(num){
if (num<=1){
return 1;
}else{
return num*fact(num-1);
}
}

以下代碼可導致出錯:
var anotherFact = fact;
fact = null;
alert(antherFact(4)); //出錯

由於fact已經不是函數了,所以出錯。
用arguments.callee可解決問題,這是一個指向正在執行的函數的指標。
新的函數為:
複製代碼 代碼如下:
function fact(num){
if (num<=1){
return 1;
}else{
return num*arguments.callee(num-1); //此處更改了。
}
}
var anotherFact = fact;
fact = null;
alert(antherFact(4)); //結果為24.


JS普通遞迴的改進

遞迴函式是在一個函數通過名字調用自身的情況下構成的,如下所示:
複製代碼 代碼如下:
function factorial(num)
{
if(num<=1)
{
return 1;
}
else
{
return num * factorial(num-1);
}
}

這是一個經典的階乘函數。表面看來沒有什麼問題,但下面的代碼卻可能導致它出錯。
var anotherFactorial = factorial;

anotherFactorial(4); //輸出 24
factorial = null;
anotherFactorial (4); //TypeError: Property 'factorial' of object [object Window] is not a function chrome 下測試
原因在於,我們定義的函數名,其實是指向函數的一個指標,此時定義了anotherFactorial 也指向了那個函數,所以調用anotherFactorial (4)可以成功的輸出24
此時 factorial = null; 那麼執行定義函數的引用就剩下了anotherFactorial,那麼在調用anotherFactorial(4)就會顯示以上的錯誤的資訊。
此時可以使用arguments.callee來替代函數定義中的 factorial,
函數的定義就變成了:
複製代碼 代碼如下:
function factorial(num)
{
if(num<=1)
{
return 1;
}
else
{
return num * arguments.callee(num-1);
}
}

那麼在使用上面的4行測試代碼,最後一行測試代碼也可以成功的輸出24.
--------------------------------------
上述的內容摘自<<JavaScript進階程式設計>>第2版 144頁 7.1節

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.