Cuando usas este código
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var y = [] x.forEach(elt => { for(let i = 0; i < elt; i++){ y.unshift(i) } }) console.log(y)sigue contando la matriz 'x' la longitud de x veces. Por favor, explícame esto.
El código está haciendo exactamente lo que le estás pidiendo que haga.
Está ejecutando un ciclo for para cada elemento en x .
Así que estás corriendo
for (let i = 0; i < x[0]; i++) ... //i goes from 0 to 0 for (let i = 0; i < x[1]; i++) ... //i goes from 0 to 1 for (let i = 0; i < x[2]; i++) ... //i goes from 0 to 2 for (let i = 0; i < x[3]; i++) ... //i goes from 0 to 3 ...Por eso obtienes esos 9...0, 8...0, 7...0, y así sucesivamente.
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let y = [] x.forEach(elt => { console.log(`For the element ${elt}`); //For each element in x, you are executing the following loop: for(let i = 0; i < elt; i++){ console.log(`unshifting ${i}...`); y.unshift(i) } console.log(`End of each element (${elt}): ${y}`); }) //if you want each element in x to unshift into y, you need to simply: const z = []; x.forEach(elem => z.unshift(elem)) console.log(z);Aquí hay una forma más limpia de lograr el mismo resultado:
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const y = [] x.forEach(n => x.slice(0, n).forEach((_, i) => y.unshift(i)))Código con explicación:
const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const y = [] // For each number in x array: x.forEach(n => // Create a new array from 0 to the current n number: // [0, ..., n] x.slice(0, n).forEach((_, i) => // And iterate adding the current i index to the beginning of y array y.unshift(i) ) ) console.log(y)