JavaScript,尾遞迴,return和eval

來源:互聯網
上載者:User
function fact_iter(product, counter, max_count){
    if(counter > max_count){
        return product;
    }
    else{
        fact_iter(counter*product , counter+1, max_count);
    }
    //return eval( (counter > max_count) ? temp = product:fact_iter(counter*product , counter+1, max_count));
}

alert(fact_iter(1,1, 6));

這樣的代碼返回的是undefined。

但是改寫成函數式寫法,就正確返回6!的值了。

eval,你懂的,在這裡面不用指明傳回值,不用聲明變數,最後一個陌生變數就是傳回值,於是正確返回了720.

把eval去掉,嗯,也能正確返回720.

說明啥來著,eval和return效果一樣啊。

還說明什麼,在JavaScript裡,在你的尾遞迴裡,你想在if語句裡面return是行不通,用三目運算的函數式寫法吧,孩子。

其實麼,也是我寫的語句有問題。正確的寫法:

function factorial(n){
    alert(fact_iter(1,1,n));
}

function fact_iter(product, counter, max_count){
    if(counter > max_count)
    {
        return product;
        
    }
    else
    {
        return fact_iter(counter*product , counter+1, max_count);
        
    }
}

factorial(6);

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.