In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to use map method functions", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use map method functions.
Background
I thought it was very simple when I looked at a written test question yesterday, but the result was not what I thought. I wrote the test question directly.
Const array = new Array (5) .map ((item) = > {return item = {name:'1'}}); console.log (array); / / Please write the output result
"my imaginary answer": [{name:'1'}, {name:'1'}]
"practical answer": [empty × 5]
Why is this happening?
Conjecture 1
The first thing that comes to mind is that new Array (5) generates an array of [undefined, undefined].
Const array = [undefined, undefined]; const newArr = array.map ((item) = > {return item = {name:'1'}); console.log (newArr); / / the result is [{name:'1'}, {name:'1'}]
"conjecture 1 error"
Conjecture 2
The array generated by new Array (5) has no value in each item, which means that a [,] such array is generated.
Const array = [,]; const newArr = array.map ((item) = > {return item = {name:'1'}}); console.log (newArr); / / the result is [empty × 5]
"guess 2 is correct."
Why
Map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. Callback is invoked only for indexes of the array which have assigned values (including undefined). It is not called for missing elements of the array; that is:
Indexes that have never been set
Which have been deleted; or
Which have never been assigned a value.
Map calls the provided callback function for each element in the array in turn, and then constructs a new array based on the result. -calls only to array indexes with assigned values (including). The callback function of the map function is called only by items that have been assigned a value. New Array (1) is different from [undefined]. New Array (1) does not assign a value to the items in the array, while [undefined] assigns an undefined value to the items in the array.
Summary
The array produced by new Array (5) is an array that has no values assigned to the items in the array. Map only makes callback calls on array indexes with assigned values (including).
Deep thinking on map method
Const array = new Array (5)
It can be understood as
Const array = [] array.length = 5
It's understandable.
Const array = [,]
But here I have a question:
When I was learning the handwritten map method,
If you take a look at Baidu, you will find that basically many people are handwritten like this:
Array.prototype.MyMap = function (fn, context) {var arr = Array.prototype.slice.call (this); / / it is not used because it is ES5. The expansion character var mappedArr = []; for (var I = 0; I)
< arr.length; i++ ){ mappedArr.push(fn.call(context, arr[i], i, this)); } return mappedArr; } 这样似乎没啥问题,但是 这个map的手写源码 根本解释不通上面返回[empty × 5]的现象。 我们可以看一下返回结果: 如图所示,我的天,这不是坑人吗! 那真正的map方法应该死怎样实现的呢? 我猜想它应该会去遍历每一项,并且判断当前项是否为empty,是的话就不执行里面的操作,「里面指的是for循环里面的代码」 好的,问题来了,怎么判断当前项是empty?确实难倒我了,为此,我们去看下map的真正源码吧! 依照 ecma262 草案,实现的map的规范如下:The following is to simulate and implement the map function step by step according to the provisions of the draft:
Array.prototype.map = function (callbackFn, thisArg) {/ / handle array type exception if (this = = null | | this = undefined) {throw new TypeError ("Cannot read property 'map' of null or undefined") } / / handling callback type exception if (Object.prototype.toString.call (callbackfn)! = "[object Function]") {throw new TypeError (callbackfn +'is not a function')} / / draft mentioned to convert to object let O = Object (this); let T = thisArg; let len = O.length > 0; let A = new Array (len); for (let k = 0; k
< len; k++) { // 还记得原型链那一节提到的 in 吗?in 表示在原型链查找 // 如果用 hasOwnProperty 是有问题的,它只能找私有属性 if (k in O) { let kValue = O[k]; // 依次传入this, 当前项,当前索引,整个数组 let mappedValue = callbackfn.call(T, KValue, k, O); A[k] = mappedValue; } } return A; ``} 这里解释一下, length >> > 0, which literally means "move 0 bits to the right", but actually fills the previous space with 0. The function here is to ensure that len is a number and an integer.
To cite a few special cases:
Null > 0 / / 0 undefined > 0 / / 0 void (0) > > 0 / / 0 function a () {}; a > > 0 / / 0 [] > 0 / / 0 var a = {}; a > > 0 / 0 / 123123 > 0 / 123123 45.2 > 0 / 450 > 0 / 0-0 > 0 / 0-1 > > 0 / / 4294967295-1212 > 0 / 4294966084
Overall, it is not that difficult to implement, but it is important to note that in is used for prototype chain lookup. At the same time, if it is not found, it will not be dealt with, which can effectively deal with sparse arrays.
Finally, I will give you the V8 source code and check it with reference to the source code. In fact, it is still very complete.
Function ArrayMap (f, receiver) {CHECK_OBJECT_COERCIBLE (this, "Array.prototype.map"); / / Pull out the length so that modifications to the length in the / / loop will not affect the looping and side effects are visible. Var array = TO_OBJECT (this); var length = TO_LENGTH (array.length); if (! IS_CALLABLE (f)) throw% make_type_error (kCalledNonCallable, f); var result = ArraySpeciesCreate (array, length); for (var I = 0; I
< length; i++) { if (i in array) { var element = array[i]; %CreateDataProperty(result, i, %_Call(f, receiver, element, i, array)); } } return result; } 我们可以看到。「其实就是用key in array 的操作判断当前是否为empty。」 可不是嘛,key都没有,当然是empty了。 另外我们不能用var arrMap的方式去初始化一个即将返回的新数组,看源码。发现是要通过new Array(len)的方式去初始化So if we implement the map method this way, we can optimize it like this.
Array.prototype.MyMap = function (fn, context) {var arr = Array.prototype.slice.call (this); var mapArr = new Array (this.length); for (var I = 0; I < arr.length; iTunes +) {if (i in arr) {mapArr.push (fn.call (context, arr [I], I, this));} return mapArr;}
Hey! I feel like I can brag when I encounter this problem in the next interview!
Why can key in Array determine whether the current item is empty?
This involves the "general properties" and "sort properties" of an object.
Since I have written articles to explain these two things before, I will not repeat them any more. you can click on this article to have a look at it, which uses a series of test questions to explain "general properties" and "sort properties".
Baidu front-end interview questions: detailed explanation of the difference between for in and for of and the output order for for in
We can see the picture in the article. Is it possible to find that 2 in bar is false because the key with 2 is not on element at all?
At this point, I believe you have a deeper understanding of "how to use map method functions". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.