简体   繁体   English

为什么我的变量引用全局范围变量?

[英]Why is my variable referencing the global scope variable?

I tried to write a function that finds all possible permutations given an array of numbers. 我试图编写一个函数,该函数查找给定数字数组的所有可能排列。 Here is my code. 这是我的代码。

var perm = [];
var usedchar = [];

function findAllPermutations(arr) {

  for (var i = 0; i < arr.length; i++) {
    var x = arr.splice(i,1)[0];
    usedchar.push(x);

    if (usedchar.length == 3) {
      perm.push(usedchar);
    }

    findAllPermutations(arr);
    usedchar.pop();
    arr.splice(i,0,x);
  }
}

findAllPermutations([1,2,3]);

console.log(perm); //-> [[],[],[],[],[],[]]

I expect to get: 我希望得到:

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Can someone explain why I'm not getting this answer? 有人可以解释为什么我没有得到这个答案吗?

perm.push(usedchar);

needs to be 需要是

perm.push(usedchar.slice());

in order to clone the usedchar array, to snapshot it at that moment. 为了克隆usedchar数组,在那一刻对其进行快照。 Otherwise, you end up with six references to usedchar that had all kinds of stuff pushed in and then popped out, ending up empty at the end. 否则,您将最终获得对usedchar六个引用, usedchar引用具有各种内容,然后又弹出,最后以空结尾。

You're using the same array that holds your intermediate result as storage for your algorithm and things are getting mixed up. 您使用的是用于存储中间结果的同一数组作为算法的存储,并且事情变得混乱起来。 You need to either separate the two or make sure you clone your usedchar array before pushing it into your perm array. 您需要将两者分开,或者确保在将其放入perm阵列之前克隆出usedchar阵列。 Something like this plunker: http://plnkr.co/edit/HQ6q8fo8S0K21cISQKVt 像这样的小家伙: http ://plnkr.co/edit/HQ6q8fo8S0K21cISQKVt

  var perm = [];
  var usedchar = [];
  var another = [];

  function findAllPermutations(arr) {


  for (var i = 0; i < arr.length; i++) {
    var x = arr.splice(i,1)[0];
    usedchar.push(x);

    if (usedchar.length == 3) {
      perm.push(usedchar.slice());
    };

    findAllPermutations(arr);
    usedchar.pop();
    arr.splice(i,0,x);
  };
};

findAllPermutations([1,2,3]);
console.log(perm);

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

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