【问题标题】:for loop provides only first or last resultfor 循环只提供第一个或最后一个结果
【发布时间】:2020-04-27 08:37:40
【问题描述】:

起初我将 return 放在 for 循环中,但只显示第一个结果。 我做了一些研究,我意识到循环最终满足了条件,因此它在第一个结果处停止。 我已经把它从循环中取出,现在它只提供最后一个结果。 这不是我第一次遇到这个问题,尽管我正在寻找解决方案,但我无法理解我做错了什么。

function diamond(n) {


  let space = " "; //spaces
  let newLine = "\n"
  let aster = "*";
  let multi = (n - 1) / 2; //variable in for loop
  let result = ""

  if ((n % 2 === 0) || n < 1) {
    return null
  } else if (n === 1) {
    return aster
  } else {

    for (let i = 0; i < multi; i++) {
      result = space.repeat(multi - i) + aster.repeat(1 + (i * 2)) + space.repeat(multi - i) + newLine;
    }
    return result // gives only the last result
  }
}

console.log(diamond(7)) //  expected "  *\n ***\n*****\n ***\n  *\n"
console.log(diamond(1)) // expected "*"
console.log(diamond(2)) // expected null

【问题讨论】:

  • 试试result += 而不是result =

标签: javascript loops for-loop return


【解决方案1】:

发生这种情况是因为您在循环的每次迭代中为变量 result 重新分配了一个新值。

您想首先将变量实例化为字符串。
然后在每次迭代时将数据连接到它。

类似这样的:

let result = '';
for (let i = 0; i < multi; i++) {
  result += space.repeat(multi - i) + aster.repeat(1 + (i * 2)) + space.repeat(multi - i) + newLine;
}
return result;

注意+= 运算符:-)

希望这会对你有所帮助。

【讨论】:

  • 非常感谢!!我已经被卡住了一段时间,我无法弄清楚!现在我明白我做错了什么!祝你有个愉快的夜晚!! :)
【解决方案2】:

正如其他人所暗示的,使用+= 将每一行附加到结果中。

function diamond(n) {


  let space = " "; //spaces
  let newLine = "\n"
  let aster = "*";
  let multi = (n - 1) / 2; //variable in for loop
  let result = ""

  if ((n % 2 === 0) || n < 1) {
    return null
  } else if (n === 1) {
    return aster
  } else {

    for (let i = 0; i < multi/2; ++i) {
      result += space.repeat(multi - i) + aster.repeat(1 + (i * 2)) + space.repeat(multi - i) + newLine;
    }
    for (let i = 0; i < multi/2 + 1; ++i) {
      result += space.repeat(i+1) + aster.repeat(1 + ((multi-1-i) * 2)) + space.repeat(i+1) + newLine;
    }
    return result // gives only the last result
  }
}

console.log(diamond(7)) //  expected "  *\n ***\n*****\n ***\n  *\n"
console.log(diamond(1)) // expected "*"
console.log(diamond(2)) // expected null

【讨论】:

  • 感谢您的提示!我没有意识到我可以同时使用result +=,然后将两者合二为一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 2012-08-15
相关资源
最近更新 更多