递归关闭 [英] Closures in recursion

查看:112
本文介绍了递归关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有这两个递归函数。
第一个函数以从右到左的顺序返回输入数字的数字
第二个函数按从左到右的顺序返回它们。

i have this two recursive functions in javascript. first function returns digits of the input number in right to left order second function returns them in left to right order.

function first(n){
    if(n > 0){
        m = Math.floor( n/10 );
        v = ( n - m * 10 ) + " " + first(m);
        return v;
    }
    return "";
}



function second(n){
    if(n > 0){
        m = Math.floor( n/10 );
        v = second(m) + " " + ( n - m * 10 );
        return v;
    }
    return "";
}

第一个函数的结果是

7 6 1 



函数是

result of the second function is

1 16 167

但我预期这

1 6 7 

我在PHP和JAVA测试了类似的代码,它工作得很好。
大概的问题是在Javascript的闭包。

I tested similar code in PHP and JAVA and it works well. Presumably the problem is in Javascript's closures. But I cant figure how to fix it.

推荐答案

这很简单:你使用隐含的全局变量:

It's perfectly simple: You're using implied globals:

function second(n)
{
    if(n > 0)
    {
        m = Math.floor( n/10 );
        //m is changing here ------\\will use lowest value of m
        v = second(m) + " " + ( n - m * 10 );
        return v;
    }
    return "";
}

修复是:

function second(n)
{
    if(n > 0)
    {
        //make declare it in the scope itself
        var m = Math.floor( n/10 );
        v = second(m) + " " + ( n - m * 10 );
        return v;
    }
    return "";
}

这仍然会带来 v 。如果我是你,我也会在本地声明 v

This still leaves you with the evil implied global v, too. If I were you, I'd declare v locally, too

function second(n)
{
    var m, v = '';
    n = +(n);//coerce to number
    if (n > 0)
    {
        m = Math.floor(n/10);
        v = second(m) + ' '+ (n-m*10);
    }
    return v;
}

此函数按预期工作。

问题没有真正要做关闭这样,但它是由 JS解析表达式/名称的方式

与JS如何处理递归函数,你得到的输出,简单和简单。

This function works as expected.
The problem didn't really have to do with closures as such, but it was caused by the way JS resolves expressions/names.
Couple that to how JS deals with recursive functions and you get the output you got, plain and simple.

JS实际上没有递归调用栈。上次我检查,递归调用有效地短路(〜= goto的)。我记得在道格拉斯·克罗克福德(Douglas Crockford)读到关于它与调用栈有关的东西。

虽然ES5的严格模式引入了TCO,并且它应该在2013年底ES6 - Harmony)。我已连结到几个网站这里 ,如果您愿意阅读更多有关此事。

JS doesn't really have a recursive call-stack, yet. Last time I checked, recursive calls were effectively short-circuited (~= goto's). I remember reading something on the subject by Douglas Crockford, about it having something to do with the call-stack.
Though ES5's strict mode does introduce TCO, and it should make it by the end of 2013 (ES6 - Harmony). I've linked to a couple of sites here, if you care to read more on the matter

这篇关于递归关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆