gpt4 book ai didi

javascript - 为什么我们在 `Number.prototype.valueOf` 函数内部使用 `map()`

转载 作者:行者123 更新时间:2023-11-28 18:31:33 25 4
gpt4 key购买 nike

以下代码:

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

创建以下数组

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

为什么map()需要Number.prototype.valueOf来将数字0压入该数组的每个位置。是否有不同的(更有效的)方法来实现这个结果,或者这是最好的方法?

最佳答案

如果您阅读 map documentation你可以阅读以下内容:

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。

您也可以这样写以获得相同的结果:

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

但是,如果您只是想用值填充数组,我认为您可以使用 Array.prototype.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);
<小时/>

性能测试:

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");

关于javascript - 为什么我们在 `Number.prototype.valueOf` 函数内部使用 `map()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37888562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com