Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - What is .map() doing in this situation?

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

[0].map(Array);

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

What is happening here?

EDIT

The reason this makes me curious is because something like

[0].map(String);

Will return

["0"];

And not

["0", "0", "String"]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

So it's like doing this:

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...