DEV Community

Lino Mattos
Lino Mattos

Posted on

3 1

Cómo crear un array de x longitud relleno de 0s en javascript.

Hace unos días necesitaba crear un array relleno de números 0. 🤔
Podía hacerlo de una manera literal declarándolo y contando los 0 que vaya ingresando:

let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

¿Está perfecto no?👌
¿Pero qué pasa si debo rellenar con 100 números 0 o cualquier otro valor? 😅

Entonces puedo apoyarme en el objeto Array() y el metodo .fill() de esta manera:

let nuevoArr = Array(90).fill(0)
Enter fullscreen mode Exit fullscreen mode

Dentro de Array() pongo la cantidad de elementos que quiero tener y en fill() el contenido que rellenará el array.

Array relleno de 0s

Aplica a cualquier tipo de contenido:

let emojiArr = Array(42).fill(String.fromCodePoint(0x1F914))
Enter fullscreen mode Exit fullscreen mode

Array relleno de emojis

let arrObjs = Array(12).fill({})
Enter fullscreen mode Exit fullscreen mode

Array relleno de objetos vacios

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more