Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11631

How to extend a given array with default values?

$
0
0

I have an array holding a bunch of booleans and a function that adds n new booleans to it. All of them should start with their default value, so one way would be

const array = [];function extendArrayBy(amountOfNewItems) {  for (let i = 0; i < amountOfNewItems; i++) {    array.push(false);  }}extendArrayBy(3);console.log(array);

but there is a Array.prototype.fill() function which might do it "more elegantly". I tried:

let array = [];const amountOfNewItems = 3;array = array.fill(false, array.length, array.length + amountOfNewItems);console.log(array);

Unfortunately the modified array does not contain the new items. Does someone know what I missed?


Viewing all articles
Browse latest Browse all 11631

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>