Necesito obtener esta salida:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15Lo que he probado hasta ahora:
function getPyramid() { let nums = 0; for (let i = 1; i <= 15; i++) { for (let n = 1; n < i; n++) { console.log(n); } console.log('<br/>'); } return nums; } getPyramid();Además de las notas proporcionadas por jnpdx en los comentarios, agregaría algunas:
i, j<br/> para HTML nueva línea, ¡en JS hacemos \n para eso!number++ es el mismo number += 1(expression)?true:false en lugar de if/else function getPyramid(Lines) { let number = 1; // the counter to display on each line of pyramid! for (let i = 1; i <= Lines; i++) { let str = '';//line to display for (let j = 1; j <= i; j++) { str += number++;//incrementing counter str += j!=i ? ' ' : ''; //to make space, but not at the end of line. } console.log(str);//display that line } } getPyramid(5); for (let i = 1 ; i <= 5; i++) { let s = [] for (let x = i * (i - 1) / 2 + 1; x <= i * (i + 1) / 2; x++) { s.push(x) } console.log(s.join(" ")) }Es posible hacerlo con un solo bucle.
function getPyramid() { let nums = 0; let count = 1; let numbers = '' for (let i = 0; i <= 15; i++) { if(count === nums){ count++ nums = 0; console.log(numbers) numbers = '' } nums ++ numbers += ' ' + (i +1) } } getPyramid(); function getPyramid(rows) { let nums = 0; let count = 1; let numbers = '' let i = 1 while (count < rows + 1 ) { if(count === nums){ count++ nums = 0; console.log(numbers) numbers = '' } nums ++ numbers += ' ' + i i++; } } getPyramid(5);