I'm a beginner and I'm struggling to understand why the word "Array" is not defined but still works. Does js know array means it should create a new array. I also don't understand why we place the parameter "n" inside it.I understand the rest except those two parts;
function(n) {
return Array(n).fill(0).map((_, idx) => idx 1);
}
console.log(fillInNumbers(5));
the console prints;//[1, 2, 3, 4, 5] kindly assist.
CodePudding user response:
Array() is the constructor function for javascript arrays. Check out this link for more on that. Array() takes an argument (in your case, n) that determines the number of elements to initialize the array to. If your n is 5, you'd have an array with 5 elements, but all of them would be undefined. fill(0) changes all of the elements to 0
CodePudding user response:
"Array" is not defined but still works
It is defined, by the browser. Array
is one of many built-in objects of JavaScript. This means that the browser has already defined what an Array
is and what it can do. This is by design.
Does js know array means it should create a new array
Calling Array(n)
like this, where n
is an integer between 0 and 2^32 - 1 (inclusive) will create a new array with as many (empty) keys as specified in n
.
I also don't understand why we place the parameter "n" inside it
n
represents the amount of slots the array should contain. These slots are then filled with the integer 0
.