recusrive函数调用如何在javascript中工作

时间:2017-10-31 15:14:31

标签: javascript python recursion

我正在尝试将这里看到的algorythm https://ideone.com/26G1fB(用python编写)移植到javascript。

def divide(arr, depth, m):
    if len(complements) <= depth:
        complements.append(2 ** (depth + 2) + 1)
    complement = complements[depth]
    for i in range(2):
        if complement - arr[i] <= m:
            arr[i] = [arr[i], complement - arr[i]]
            divide(arr[i], depth + 1, m)

m = int(raw_input())

arr = [1, 2]
complements = []

divide(arr, 0, m)
print arr

我对此表示赞同:

var bracketize = function(arr, depth, m) {
  if (complements.length <= depth) {
    complements.push(2 ** (depth +2) + 1)
    }
    var complement = complements[depth]

  for ( i = 0; i < 2; i++ ) {   
    if (complement - arr[i] <= m) {
      arr[i] = [arr[i], complement - arr[i]]      
      bracketize(arr[i], depth + 1 , m)
    }
  }
}

var m = 16
var arr = [1, 2]
var complements = []

bracketize(arr, 0, m)

console.log(JSON.stringify(arr))

// expected result [[[[1, 16], [8, 9]], [[4, 13], [5, 12]]], [[[2, 15], [7, 10]], [[3, 14], [6, 11]]]]
// actual result : [[[[1,16],8],4],2]

这里有一个jsfiddle https://jsfiddle.net/9umgwhoa/

这似乎是js对python进行递归调用的方式,但我无法弄清楚是什么。

任何关于2代码之间差异的指针都将受到赞赏

1 个答案:

答案 0 :(得分:2)

基本上你需要一个局部变量i。如果没有你创建一个全局变量,任何循环都会增加变量,而不考虑本地范围。

var bracketize = function (arr, depth, m) {
    if (complements.length <= depth) {
        complements.push(2 ** (depth + 2) + 1)
    }
    var complement = complements[depth],
        i;

    for (i = 0; i < 2; i++) {
        if (complement - arr[i] <= m) {
            arr[i] = [arr[i], complement - arr[i]];
            bracketize(arr[i], depth + 1, m);
        }
    }
};

var m = 16,
    arr = [1, 2],
    complements = [];

bracketize(arr, 0, m);

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