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

标签 javascript arrays types 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()需要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/

相关文章:

javascript - 如何按字段名称列出 JavaScript 对象的属性

javascript - 如何在 Firebase 中构建数据?

c++我可以用double初始化一个float类型的变量吗?

javascript - 简单的游戏循环 Socket.io + Node.js + Express

javascript - 温泉 UI 分页 : navigator and tabbar

php - 如何使用 PHP 和简单的 HTML DOM 实现多个数组(+形成)

python - 使用 np.log(array) 时忽略负值

java - 一旦输入 int <= 0,如何阻止二维 int 数组输出其值?

typescript 类不实现接口(interface)类型

c++ - 模板:获取类型并映射到函数