为什么我们在`map()`函数中使用`Number.prototype.valueOf` [英] Why do we use `Number.prototype.valueOf` inside of a `map()` function
问题描述
以下代码:
let resultsArray = Array.apply(null, Array(10)).map(Number.prototype.valueOf,0);
创建以下数组
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
为什么map()只需要将数字0推入此数组的每个位置,都需要Number.prototype.valueOf
.有没有其他方法(更有效)来达到这个结果,或者这是最好的方法?
Why does map() need Number.prototype.valueOf
just to push the number 0 in to each position of this array. Is there a different (more efficient) way to achieve this result, or is this the best way?
推荐答案
If you read the map documentation you can read this:
map()方法创建一个新数组,其结果是对该数组中的每个元素调用提供的函数.
The map() method creates a new array with the results of calling a provided function on every element in this array.
因此,您需要在第一个参数中使用函数 Number.prototype.valueOf ,在第二个可选参数中使用Number对象来填充新数组. Number对象用作第一个参数的this.
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.
fill()方法使用静态值填充数组的所有元素,从开始索引到结束索引.
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");
这篇关于为什么我们在`map()`函数中使用`Number.prototype.valueOf`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!