我的函数返回undefined(JavaScript)

时间:2018-05-02 15:10:38

标签: javascript function recursion

我正在测试一个函数,它只是进行计算并测试它是否符合标准。它正在返回undefined,我不明白为什么。我在console.log(2)之前推出了return true,它将2记录到控制台但不返回true。我是JavaScript的新手,请帮忙。

const cenas = [
  [1, 150, 3, 0, 0, 0, 2, 0],
  [2, 126, 1, 0, 2, 0, 3, 0],
  [3, 99, 1, 0, 0, 0, 2, 0],
  [4, 249, 1, 0, 0, 0, 2, 0]
];
let nC = 4;
let nA = 2;
let soma = 0;
for (let i = 0; i < nC; i++) {
  soma = soma + cenas[i][1];
}
let media = soma / nA;
let tolerancia = 0.5;
let nextStep = [1, 1, 2, 2];
let animador = 1;

const distribution = function(animador) {
  let indexes = [];
  let position = 0;
  let index = 0;
  for (let i = 0; index >= 0; i++) {
    index = nextStep.indexOf(animador, position);
    position = index + 1;
    if (index >= 0) {
      indexes.push(index);
    }
  }
  let soma = 0;
  for (i = 0; i < indexes.length; i++) {
    soma = soma + cenas[indexes[i]][1];
  }
  let criterio = Math.abs((soma - media) / media);
  if (criterio > tolerancia) {
    console.log(0)
    return false
  } else {
    console.log(1)
    if (animador >= nA) {
      console.log(2)
      return true
    } else {
      animador++;
      distribution(animador);
    }
  }
}

console.log(distribution(animador))

1 个答案:

答案 0 :(得分:0)

在JavaScript中,每个函数的末尾都有一条不可见的行。它是return undefined;,以防您忘记在代码中的所有不同分支中都有return个语句。

如果您使用了具有编码标准设置(例如airbnb)的正确IDE,它会告诉您distribution因为criterio > tolerancia === falseanimador >= nA === false递归而导致Math.abs((soma - media) / media);被破坏,但没有做任何事情。结果。这是死代码。

想象一下,您执行了let criterio = Math.abs((soma - media) / media);而不是distribution(animador + 1);。这有什么用呢? 与return distribution(animador + 1); 一样多你需要以某种方式使用结果,通过将其设置为变量或返回它。

const distribution = function (animador) {
    const indexes = [];
    let position = 0;
    let index = 0;
    for (let i = 0; index >= 0; i++) {
        index = nextStep.indexOf(animador, position);
        position = index + 1;
        if (index >= 0) {
            indexes.push(index);
        }
    }
    let soma = 0;
    for (let i = 0; i < indexes.length; i++) {
        soma += cenas[indexes[i]][1];
    }
    const criterio = Math.abs((soma - media) / media);
    if (criterio > tolerancia) {
        console.log(0);
        return false;
    }
    console.log(1);
    if (animador >= nA) {
        console.log(2);
        return true;
    }
    distribution(animador + 1);
    return undefined;
};

在修复了我的WebStorm与ESLint并启用了airbnb预设后的一些观点之后的代码:

function testFunction() {
  return this.win.get.value1 === 'test' && this.win.get.value2 === 'test1';
}

我还没有真正解决这个问题,但现在看起来要容易得多。