递归中的一元运算符前缀执行未按预期工作

unary operator prefix execution in recursion is not working as expected

我正在尝试计算给定范围内的组合数量和组合长度。这是以下代码。

function generateCombination() {
  const perm = [];
  const permLength = 2;
  const numberRange = 8;
  let total = 0;

  const getCombinations = (result, permLength, numberRange) => {
    if (result.length === permLength) {
      //console.log('result: ', result);
      return 1;
    }
  
    for (var i = 0; i < numberRange; i++) {
      if (result.indexOf(i) === -1) {
        result.push(i);
        total = total + getCombinations(result, permLength, numberRange);
        result.pop();
      }
    }

    return 0;
  }
  
  getCombinations(perm, permLength, numberRange);
  console.log("total: ", total); // expected value "total:  56"
}

generateCombination();

total 变量的控制台日志始终打印 0。但以下代码按预期工作,for 循环代码几乎没有变化。我不明白这里的前缀是如何工作的(somex = somex + fn())。有人可以帮忙吗?

// working solution
function generateCombination() {
  const perm = [];
  const permLength = 2;
  const numberRange = 8;
  let total = 0;

  const getCombinations = (result, permLength, numberRange) => {
    if (result.length === permLength) {
      //console.log('result: ', result);
      return 1;
    }
  
    for (var i = 0; i < numberRange; i++) {
      if (result.indexOf(i) === -1) {
        result.push(i);
        if (getCombinations(result, permLength, numberRange)) {
           total += 1;
        }
        result.pop();
      }
    }

    return 0;
  }
  
  getCombinations(perm, permLength, numberRange);
  console.log("total: ", total); // expected value is "total: 56" and working here
}

generateCombination();

我的问题是,我不明白为什么解决方案 1(第一个)没有按预期工作(将 total 打印为 0 而不是 56 )?

谢谢

您可以在退出时将 total 移动到 getCombinations 和 return 这个值。

function generateCombination() {
  const perm = [];
  const permLength = 2;
  const numberRange = 8;

  const getCombinations = (result, permLength, numberRange) => {
    if (result.length === permLength) return 1;

    let total = 0;
  
    for (let i = 0; i < numberRange; i++) {
      if (result.indexOf(i) === -1) {
        result.push(i);
        total += getCombinations(result, permLength, numberRange);
        result.pop();
      }
    }

    return total;
  }
  
  console.log("total: ", getCombinations(perm, permLength, numberRange)); // expected value "total:  56"
}

generateCombination();