Javascript 递归函数。将数据存储在数组中时出现错误结果

标签 javascript arrays function recursion

在尝试使用堆算法获取所有排列时,我遇到了将结果存储在数组中的问题。

生成的结果是(来自console.log(arr);)
[“1”、“2”、“3”]
[“2”、“1”、“3”]
[“3”、“1”、“2”]
[“1”、“3”、“2”]
[“2”、“3”、“1”]
[“3”、“2”、“1”]

但只有最后一个值存储在 arr 中,并且以某种方式存储的数组是这样的(来自 console.log(JSON.stringify(allPermutations)); )
[“3”、“2”、“1”]
[“3”、“2”、“1”]
[“3”、“2”、“1”]
[“3”、“2”、“1”]
[“3”、“2”、“1”]
[“3”、“2”、“1”]

var allPermutations = [];

function swap(arr,index1,index2){
    var dummy = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = dummy;
    return arr;
}

function generate(n,arr){
    if(n==1){
        console.log(arr);
            //result:
            //["1", "2", "3"]
            //["2", "1", "3"]
            //["3", "1", "2"]
            //["1", "3", "2"]
            //["2", "3", "1"]
            //["3", "2", "1"]
        allPermutations.push(arr);
    }else{
        for(var i=0;i<n-1;i++){
            generate(n-1,arr);
            if( n%2 ==0){
                arr = swap(arr,i,n-1);
            }else{
                arr = swap(arr,0,n-1);
            }
        }
        generate(n - 1, arr);
    }
}

generate(3,['1','2','3']);

console.log(JSON.stringify(allPermutations));
/*result:
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]*/

这是怎么回事?很想了解。谢谢

最佳答案

allPermutations.push(arr) 替换为 allPermutations.push(arr.slice())

问题是,您一直在推送同一个数组,然后更改该数组。当你推送一个数组时,你不会推送它的副本:你推送一个引用。只有一个数组,以及对它的六个引用;当你读出它们时,它们读起来都是一样的,因为它们都是同一个数组

.slice() 将为您提供一个包含相同元素的新数组;这样,您会在结果中得到六个新数组,而不是同一数组的六次提及。

来 self 之前的一个几乎但不完全重复的答案,我喜欢这个比喻:

As a metaphor, imagine a theatre director in casting. He turns to an actor, says "You... you'll be Romeo.". Then he looks at the same actor, says "You... you'll be Mercutio. Here, Mercutio, take this sword. Romeo... who told you to get a sword?!?" completely failing to realise that, if Romeo and Mercutio are the same person, if one of them picks up a sword, the other does it too.

关于Javascript 递归函数。将数据存储在数组中时出现错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36145102/

相关文章:

javascript - 在手机网站实现 "Add to Home Screen"。是否可以?

javascript - fitBounds() 显示整个地球(如果 map 先隐藏然后显示)

javascript - 纯CSS关闭按钮

javascript - 如何检查此函数中是否至少选中了一个单选按钮?

javascript - 字符串加密 - 生成独特的模式,如 Spotify 代码

c++ - 如何在 C++ 中找出二维 int 数组的大小?

c++ - 将数组从 C++ 构造函数传递给函数

javascript - 在函数内部创建方法

javascript - 递归返回函数以形成嵌套函数 - Javascript

function - 在涉及积分的matlab中绘制函数