【问题标题】:Node.js somehow changes my Object with recursive functionNode.js 以某种方式用递归函数改变了我的对象
【发布时间】:2017-02-17 22:29:35
【问题描述】:

我不知道我做错了什么,但是在第一次执行后这段代码改变了我的recipesData对象,在第二次执行时我得到了非常大的变量(因为代码使用recipesData) .

如果我使用调试器对象(recipesData)从这里开始改变:

 child[child_part] *= craft[part];

child 甚至是另一个与recipesData 无关的变量。

这是我使用的代码:

first ex. second execute.
282       11340
336       69498
390       108918
82        3400
82        3397
27        745
270       10629090
27        19683

// Some object with date
var recipesData = {
    'test1': {
        'example1': 544,
        'example2': 323
    },
    'test2': {
        'example1': 123
    },
}

// Function that I call from main file
module.exports.getFinished = function (item, stock) {
    // Create temp 'recipes' variable
    var recipes = recipesData[item];
    // Execute recursive func
    var basics = getBasics(recipes);

    return basics;
};

// Create 'finished' empty object
var finished = {};

// My recursive fuction that works pretty nice at first
function getBasics(craft) {
    for (var part in craft) {
        for (var recipe in recipesData) {
            if (recipesData.hasOwnProperty(part)) {
                var child = recipesData[part];
                break;
            } else
                child = null;
        }

        if (child) {
            for (var child_part in child)
                // HERE it's CHANGE my 'recipesData' object at the top!
                child[child_part] *= craft[part];
            getBasics(child);
        } else {
            if (finished.hasOwnProperty(part))
                finished[part] += craft[part];
            else
                finished[part] = craft[part];
        }
    }
    return finished;
}

【问题讨论】:

    标签: javascript node.js object recursion scope


    【解决方案1】:

    JavaScript 中的对象是通过引用而不是值传递的。在getBasics 内部,craft 是对与recipeData 相同的基础数据的引用。 child 是对recipeData 的内部对象之一的引用。

    因此,当您使用*=child 中的属性分配新值时,它对recipeData 变量引用的相同数据进行操作。

    【讨论】:

    • 感谢您的回答,我理解了主要思想,但仍然不知道如何解决它,没有像制作真实副本这样的解决方法......
    【解决方案2】:

    下面的Child只是对recipesData的引用。

    if (recipesData.hasOwnProperty(part)) {
                var child = recipesData[part];
                break;
            } else
                child = null;
        }
    

    因此稍后会修改实际的 recipesData。如果你想拥有数组的真实副本,你可以这样做,例如与 slice() 或与 concat() 类似:

    child = [].concat(recipesData[part]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      相关资源
      最近更新 更多