• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

294
Views
¿Cómo crear una matriz de tamaño N con el tamaño de N (x) y llenarla con los números en un rango de 0 a 100 al azar?

¡Hola, comunidad de StackOverflow! Mi nombre es Piet.

Mientras investigaba el amado Javascript me quedé un poco atascado:

No estoy seguro de por qué recibo 98 elementos vacíos en mi matriz.

En Index[0] e Index[99] obtengo IntegerValues como se esperaba.

¡Gracias por sus respuestas! :)

 // create an Array with the size of N(x) and // fill it with numbers in a range from 0 to 100 randomly. createNSizedArray = (x) => { for(let i = 0; i < x; i++) { var arr = []; arr[i] = arr.push(Math.round(Math.random()*100)); } return arr; } console.log(createNSizedArray(100)); // output -> [ 31, <98 empty items>, 1 ]; // Why are the other 98 items in the Array empty and how to change them into integer values?

En realidad, inspeccioné los artículos [1-98] para averiguar sus valores y verificar si realmente están vacíos.

Pero:

console.log(arr[4]) por ejemplo, devuélveme "indefinido". Así que no están realmente vacíos.

about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Está obteniendo una matriz en su mayoría indefinida porque está definiendo una nueva variable arr en cada iteración. Debe mover la declaración de arr fuera del bucle.

Aquí hay una alternativa rápida: Array(100).fill().map(_=>Math.round(Math.random()*100))

about 3 years ago · Juan Pablo Isaza Report

0

Intente mover la inicialización de la matriz antes del bucle for. Esto asegura que no cree una nueva matriz cada vez que se ejecuta el bucle.

about 3 years ago · Juan Pablo Isaza Report

0

Es porque está creando una nueva matriz en cada iteración. Prueba esto:

 createNSizedArray = (x) => { var arr = []; for (let i = 0; i < x; i++) { arr[i] = arr.push(Math.round(Math.random() * 100)); } return arr; };
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error