Why do we use `Number.prototype.valueOf` inside of a `map()` function

后端 未结 3 1110
时光说笑
时光说笑 2021-01-17 07:21

The following code:

let resultsArray = Array.apply(null, Array(10)).map(Number.prototype.valueOf,0);

creates the following array

         


        
3条回答
  •  清歌不尽
    2021-01-17 07:38

    In your code, 0 is passed to Number.prototype.valueOf which just returns the primitive (0).

    Which is essentially the same thing as

    Number.prototype.valueOf.call(0)
    

    If your code was:

    let resultsArray = Array.apply(null, Array(10)).map(Number.prototype.valueOf,10);
    

    The map() function would essentially be calling Number.prototype.valueOf like this:

    Number.prototype.valueOf.call(10)
    

    Here's the documentation - which provides a nice Polyfill that you can read and see exactly what map() is doing.


    Strings would look like this:

    Array.apply(null, Array(10)).map(String.prototype.valueOf,"10")
    

    Which would output:

    ["10", "10", "10", "10", "10", "10", "10", "10", "10", "10"]
    

    But surely you can do it in a more tricky way ;)

    var resultsArray = '0'.repeat(10).split('').map(Number);
    console.log(resultsArray);

    And in case it's not necessary to get the numbers (but strings), it's even shorter:

    var resultsArray = '0'.repeat(10).split('');
    console.log(resultsArray);

提交回复
热议问题