简体   繁体   中英

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/

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.

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

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.

  2. White space is not preserved in HTML, you can insert the text into a pre tag where the white spaces are preserved.

  3. You are getting max stack exceeded error because you are not initializing the variable row . You can initialize this variable the same way you initialized level variable!

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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