递归推送仅添加最后一个元素

时间:2019-01-02 13:06:37

标签: javascript

我正在尝试创建一个函数,该函数生成给定长度的列表中元素的所有组合,并在2D列表中返回它们(例如,元素[1、2、3]和长度2的结果为[[1、1 ],[1、2],[1、3],[2、1],...]),但是在实现此功能时遇到问题。结果列表是正确的长度,但是列表中的所有项目都是找到的最后一个(因此,对于上面的项目,我得到了[[3,3],[3,3],[3,3],...])。

我认为这是因为JavaScript不会立即推送,而只是推送到函数的末尾,因此对象已经发生了变异,但无法想到解决方法。我该如何立即推动它?

function combinationRecursive(maxLength, position, current, elements) {
    if (position >= maxLength) {
        combinations.push(current);
        return;
    }
    for (var i = 0; i < elements.length; i++) {
        current[position] = elements[i];
        combinationRecursive(maxLength, position + 1, current, elements);
    }
    return;
}

// example usage
combinations = [];
// max length 2 using 1,2,3 as described above
// the 0 and [] are the default starting parameters. I plan to add a wrapper function later
combinationRecursive(2, 0, [], [1,2,3]);

1 个答案:

答案 0 :(得分:1)

您正在重用相同的数组,最后在结果的所有项目中获得相同的数组。

您可以推送具有相同对象引用的数组副本,而不是原始数组。

function combinationRecursive(maxLength, position, current, elements) {
    if (position >= maxLength) {
        combinations.push(current.slice());
        return;
    }
    for (var i = 0; i < elements.length; i++) {
        current[position] = elements[i];
        combinationRecursive(maxLength, position + 1, current, elements);
    }
}

// example usage
combinations = [];
// max length 2 using 1,2,3 as described above
// the 0 and [] are the default starting parameters. I plan to add a wrapper function later
combinationRecursive(2, 0, [], [1, 2, 3]);

console.log(combinations);
.as-console-wrapper { max-height: 100% !important; top: 0; }