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

后端 未结 3 1108
时光说笑
时光说笑 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:37

    If you read the map documentation you can read this:

    The map() method creates a new array with the results of calling a provided function on every element in this array.

    So you need to use the function Number.prototype.valueOf in first parameter and a Number object in second optional parameter to fill the new array. The Number object is used as the this of the first parameter.

    You can also write this for the same result:

    let resultsArray = Array.apply(null, Array(10)).map(function(){return 0;});
    

    But if you juste want to fill an array with a value, I think you may use the Array.prototype.fill method.

    The fill() method fills all the elements of an array from a start index to an end index with a static value.

    let resultsArray = (new Array(10)).fill(0);
    

    Performance test:

    var start, stop, array;
    var iteration = 100000;
    
    
    // Map
    start = Date.now();
    array = Array.apply(null, Array(iteration)).map(Number.prototype.valueOf,0);
    stop = Date.now();
    console.log("Map executed in "+(stop-start)+"ms");
    
    // Map simple array
    start = Date.now();
    array = (new Array(iteration)).map(Number.prototype.valueOf,0);
    stop = Date.now();
    console.log("Map simple array executed in "+(stop-start)+"ms");
    
    // Map simple function
    start = Date.now();
    array = (new Array(iteration)).map(function(){return 0;});
    stop = Date.now();
    console.log("Map simple function executed in "+(stop-start)+"ms");
    
    // Array.from - ES6 from @Zohaib ijaz
    start = Date.now();
    array = Array.from(new Array(iteration), () => 0)
    stop = Date.now();
    console.log("Array.from - ES6 from @Zohaib ijaz executed in "+(stop-start)+"ms");
    
    // Array.from - Non-ES6 from @Zohaib ijaz
    start = Date.now();
    array = Array.from(new Array(iteration), function(){return 0;})
    stop = Date.now();
    console.log("Array.from - Non-ES6 from @Zohaib ijaz executed in "+(stop-start)+"ms");
    
    // repeat-split-map by @nicael
    start = Date.now();
    array = '0'.repeat(iteration).split('').map(Number);
    stop = Date.now();
    console.log("repeat-split-map by @nicael executed in "+(stop-start)+"ms");
    
    // Fill
    start = Date.now();
    array = (new Array(iteration)).fill(0);
    stop = Date.now();
    console.log("Fill executed in "+(stop-start)+"ms");

提交回复
热议问题