How to use recursion to write a function to achieve the effect of js's Array.prototype.fill () method

comes from an interview question. I haven"t thought about it for a long time.

the title is as follows
function fill (n, m) {
    //
}
console.log(fill(3, 4))    // [4,4,4]

to implement

with recursion

Please let me know!

Mar.16,2021

function fill (n, m) {
    n--
    if(n) {
        return [m].concat(fill(n, m))
    } else {
        return m
    }
}
The

PS: Array.prototype.fill () method is not like this.


first of all, you need to know the fill implementation of array, file (v [, start [, end]]) where v is the value to be replaced, start is the start position, and end is the end position, that is, elements from start to end are always replaced with v in the array.
if you ask for the title, this is not the case at all.

Menu