简体   繁体   English

将Javascript局部变量设置为全局以进行递归循环

[英]Make Javascript local variable to global for recursive loops

I have a recursive function which has a local variable. 我有一个递归函数,它有一个局部变量。 It calls itself on specific condition. 它在特定条件下自称。 The local variable needs to be updated, but every call it creates a new local variable specific to the current function scope. 需要更新局部变量,但每次调用它都会创建一个特定于当前函数范围的新局部变量。 How can i reach the local variable for access all recursive loop and not to create a new one? 如何访问本地变量以访问所有递归循环而不创建新循环? Something like __Callee.varname? 像__Callee.varname这样的东西?

The code is: 代码是:

var addAttribute = function(object,elem)
{
    var attributes = [];

    // only attribute without values
    if ( object instanceof Array )
    {
        for ( var value in object )
        {
            attributes.push(object[value]);
        }
    }
    // attribute with values
    else if ( object instanceof Object )
    {
        for ( var key in object )
        {
            if ( object[key] instanceof Array )
            {
                addAttribute(object[key],elem);
            }
            else
            {
                attributes.push(key+'=\''+object[key]+'\'');
            }
        }
    }
    // Only one attribute
    else if ( typeof object === 'string' )
    {
        attributes.push('\''+object+'\'');
    }
    // Invalid parameter
    else
    {
        console.log('Invalid parameter: '+typeof object);
    }

    console.log('<'+elem+' '+attributes.join(' ').toString()+' />');

}

I do not want to make variable to global because of using this name in other functions and global scope already. 由于在其他函数和全局范围中使用此名称,我不想将变量设置为全局变量。

Use a closure 使用封闭物

function fn() {
    function recursiveFunction() {
        // do something with x
        recursiveFunction();
    }
    var x = 0;
    recursiveFunction();
}

The usual thing is to pass it into the function, possibly optionally: 通常的做法是将它传递给函数,可能可选:

var addAttribute = function(object,elem, attributes) {
    attributes = attributes || [];
    // ....

Then when calling it recursively, pass in the third argument: 然后在递归调用它时,传入第三个参数:

addAttribute(object[key], value, attributes);

Here's a much simplified example demonstrating: 这是一个简化的例子,展示了:

 function foo(num, array) { array = array || []; array.push(num); console.log("Pushed " + num + ", array = " + JSON.stringify(array)); if (num < 5) { foo(num + 1, array); } } foo(1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM