简体   繁体   English

意外令牌-递归打印圣诞树

[英]unexpected token - doing recursive to print christmas tree

What's wrong with my code below? 我下面的代码有什么问题? Couldn't spot any problem on my end. 我找不到任何问题。 https://jsfiddle.net/rz8y6vc7/ https://jsfiddle.net/rz8y6vc7/

function pyramid(n, row, level = '') {
  if (row === n) {
    return;
  }

  if (level.length === 2 * n - 1) {
    return pyramid(n, row + 1);
  }

  const midpoint = Math.floor((2 * n - 1) / 2);
  let add;
  if (midpoint - row <= level.length && midpoint + row => level.length) {
    add = '#';
  } else {
    add = ' ';
  }
  pyramid(n, row, level + add);
}

pyramid(4)

Got error on this line. 在此行出现错误。 if (midpoint - row <= level.length && midpoint + row => level.length) {

=> is not an operator in JavaScript. =>不是JavaScript中的运算符。

You may be thinking of <= , which is the smaller-than-or-equal-to operator. 您可能会想到<= ,它是小于或等于运算符。

You may read more about this particular operator here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than__or_equal_operator 您可以在此处了解有关此特定运算符的更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than__or_equal_operator

The problems with your code are: 您的代码存在以下问题:

  1. You are not printing the output into the browser, I am using document.write() to show the output. 您没有将输出打印到浏览器中,我正在使用document.write()来显示输出。

  2. White space is not preserved in HTML, you can insert the text into a pre tag where the white spaces are preserved. HTML中不保留空格,您可以将文本插入保留空格的pre标记中。

  3. You are getting max stack exceeded error because you are not initializing the variable row . 由于未初始化变量row max stack exceeded error了“ max stack exceeded error You can initialize this variable the same way you initialized level variable! 您可以像初始化level变量一样初始化该变量!

Please refer the below code snippet where it works and let me know if you face any issues implementing! 请参考下面的代码片段,该代码片段在哪里起作用,如果您在执行过程中遇到任何问题,请告诉我!

 function pyramid(n, row = 0, level = '') { if (row === n) { return; } if (level.length === 2 * n - 1) { document.getElementById("test").innerHTML += "\\n"; return pyramid(n, row + 1); } const midpoint = Math.floor((2 * n - 1) / 2); let add; if (midpoint - row <= level.length && midpoint + row >= level.length) { add = '#'; } else { add = ' '; } document.getElementById("test").innerHTML += add; pyramid(n, row, level + add); } pyramid(4) 
 <pre id="test"></pre> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM