什么是.map()在这种情况下做什么? [英] What is .map() doing in this situation?

查看:186
本文介绍了什么是.map()在这种情况下做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Chrome控制台,这是我的输入和输出:

Using the Chrome Console, this is my input and output:

[0].map(Array);

[[0, 0, [0]]]; // output

这里发生了什么?

编辑

这让我很好奇的原因是因为像

The reason this makes me curious is because something like

[0].map(String);

将返回

["0"];

而不是

["0", "0", "String"]


推荐答案

.map()函数用三个参数调用 Array()函数,数组元素的值是是 0 ,该元素的索引,也是 0 ,以及对整个数组的引用。

The .map() function is calling the Array() function with three arguments, the value of the array element which is 0, the index of that element, also 0, and a reference to the whole array.

所以就像这样:

var a = [0];
var index = 0
Array(a[index], index, a);   // create array with three elements

Array()返回的数组然后成为 .map()创建的数组的第一个元素,因此在中[[]嵌套的额外级别[[ 0,0,[0]]] 结果。

The array returned by Array() then becomes the first element of the array that .map() creates, hence the extra level of nesting in your [[0, 0, [0]]] result.

关于编辑的编辑:当你说 [0]时.map(String); 导致使用相同的三个参数调用 String(),如 String(a [ index],index,a),但 String()函数忽略除第一个参数以外的所有参数,而 Array( )使用所有提供的参数。

EDIT regarding your edit: when you say [0].map(String); that results in String() being called with the same three arguments like String(a[index], index, a), but the String() function ignores all but the first argument, whereas Array() uses all supplied arguments.

这篇关于什么是.map()在这种情况下做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆