JavaScript双递归调用,如何传回结果?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript双递归调用,如何传回结果?相关的知识,希望对你有一定的参考价值。

我有一段javascript代码,它调用递归方法两次,结果无法传回:

var subSum = (nums, target) => {
    var res = [];
    var chosen = [];
    subSets(nums, chosen, target, res);
    return res;
};

var subSets = (nums, chosen, target, res) => {
  if (nums.length === 0) {
    if (sumAry(chosen) == target) {
        console.log(array2Str(chosen));
        res.push(chosen);
    }
    //console.log(array2Str(chosen));
  } else {
    let it = nums[0];
    nums.shift();
    chosen.push(it);
    subSets(nums, chosen, target, res);

    chosen.pop();
    subSets(nums, chosen, target, res);
    nums.unshift(it);
  }
};
var array2Str = (ary) => {
    if (!ary || ary.length < 1) return '';
    let res = [];
    arrayToStr(ary, res);
    return res.join("");
};
var arrayToStr = (ary, res) => {
    res.push('[');
    for(let i = 0; i < ary.length; i ++) {
        let it = ary[i];
        if (Array.isArray(it)) {
            arrayToStr(it, res);
            if (i != ary.length - 1) {
                res.push(', ');
            }

        } else {
            res.push( (i == ary.length - 1) ? `${it}` : `${it}, `);
        }
    }
    res.push(']');
};

测试代码是:

let nums = [5,3,1,2,4,6];
console.log(`array2Str(subSum(nums, 7))`);

输出是:

Debugger attached.
[5, 2]
[3, 4]
[1, 2, 4]
[1, 6]
[[], [], [], []]

您可以看到最后一行是结果数组(res)的转储,并且4子数组的内容是空的,但根据上面的控制台日志,这些值被推送到结果数组中。无论如何,如果我注释掉最后一个subSets递归调用,最终结果打印将不会为空。有关如何通过两次递归调用传回结果的任何想法?我尝试了一个全局数组容器,它也没有。

答案

数组是通过引用传递的,这种方式正在被覆盖。使用像字符串这样的基本类型,或者选择浅层复制数组。

为此改变了推动力

      res.push(chosen.slice())  // for shllow copy

      res.push(chosen.join())  // for using primitive string

// i assume that the missing sumAry function shuld do ..
const sumAry = array => array.reduce((a, b) => a + b, 0)


var subSum = (nums, target) => {
  var res = []
  var chosen = []
  subSets(nums, chosen, target, res)
  return res
}

var subSets = (nums, chosen, target, res) => {
  if (nums.length === 0) {
    if (sumAry(chosen) == target) {
      console.log(array2Str(chosen))
      res.push(chosen.slice()) 
      // res.push(chosen.join()) 
    }
  } else {
    let it = nums[0]
    nums.shift()
    chosen.push(it)
    subSets(nums, chosen, target, res)

    chosen.pop()
    subSets(nums, chosen, target, res)
    nums.unshift(it)
  }
}
var array2Str = ary => {
  if (!ary || ary.length < 1) return ''
  let res = []
  arrayToStr(ary, res)
  return res.join('')
}
var arrayToStr = (ary, res) => {
  res.push('[')
  for (let i = 0; i < ary.length; i++) {
    let it = ary[i]
    if (Array.isArray(it)) {
      arrayToStr(it, res)
      if (i != ary.length - 1) {
        res.push(', ')
      }
    } else {
      res.push(i == ary.length - 1 ? `${it}` : `${it}, `)
    }
  }
  res.push(']')
}

let nums = [5, 3, 1, 2, 4, 6]
console.log(array2Str(subSum(nums, 7)))

以上是关于JavaScript双递归调用,如何传回结果?的主要内容,如果未能解决你的问题,请参考以下文章

javascript函数怎么自己调用自己啊?

递归的结果在javascript中存储在哪里?

JavaScript递归原理

javascript 在 Javascript 中进入无限循环和递归调用时如何调试它?

ajax后台传回结果和数据

javaScript 递归 闭包 私有变量