日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
一道JS筆試題,刷新了我對map方法函數(shù)的認(rèn)知,你做對了嗎?

 背景

昨天在看一道筆試題的時候本以為很簡單,但是結(jié)果不是我想象的那樣,直接上筆試題。

 
 
 
 
  1. const array = new Array(5).map((item) => {
  2.   return item = {
  3.     name: '1'
  4.   }
  5. });
  6. console.log(array);
  7. // 請寫出輸出結(jié)果

「我想象的答案」:[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];

「實(shí)際的答案」:[empty × 5]

為什么會這樣了?

猜想1

我第一個想到的是new Array(5)生成的數(shù)組是[undefined, undefined, undefined, undefined, undefined]。

 
 
 
 
  1. const array = [undefined, undefined, undefined, undefined, undefined];
  2. const newArr = array.map((item) => {
  3.   return item = {
  4.      name: '1'
  5.    }  
  6. });
  7. console.log(newArr);
  8. // 結(jié)果是[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];

「猜想1錯誤」

猜想2

new Array(5)生成的數(shù)組在每一項(xiàng)都沒有值,意思就是生成了[,,,,,]一個這樣的數(shù)組。

 
 
 
 
  1. const array = [,,,,,];
  2. const newArr = array.map((item) => {
  3.   return item = {
  4.      name: '1'
  5.    }  
  6. });
  7. console.log(newArr);
  8. // 結(jié)果是[empty × 5];

「猜想2正確」

為什么

  • 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依次為數(shù)組中的每個元素調(diào)用一次提供的callback函數(shù),然后根據(jù)結(jié)果構(gòu)造一個新的數(shù)組。-----僅對已分配值(包括)的數(shù)組索引進(jìn)行調(diào)用----。map函數(shù)的回調(diào)函數(shù)只會被賦過值的項(xiàng)調(diào)用。new Array(1) 和 [undefined]不一樣。new Array(1)沒有為數(shù)組中的項(xiàng)賦過值,而[undefined]為數(shù)組中的項(xiàng)賦了一個undefined值。

總結(jié)

new Array(5)產(chǎn)生的數(shù)組是一個沒有為數(shù)組中的項(xiàng)賦過值的數(shù)組。map僅對已分配值(包括)的數(shù)組索引進(jìn)行callback調(diào)用。

對map方法的深入思考

 
 
 
 
  1. const array = new Array(5)

可以理解成

 
 
 
 
  1. const array = []
  2. array.length = 5

也可以理解

 
 
 
 
  1. const array = [,,,,,]

但是這里讓我產(chǎn)生一個疑問:

以前我學(xué)習(xí) 手寫map方法的時候

你百度一下,會發(fā)現(xiàn)也基本上很多人都是這樣手寫的:

 
 
 
 
  1. Array.prototype.MyMap = function(fn, context){
  2.   var arr = Array.prototype.slice.call(this);//由于是ES5所以就不用...展開符了
  3.   var mappedArr = [];
  4.   for (var i = 0; i < arr.length; i++ ){
  5.     mappedArr.push(fn.call(context, arr[i], i, this));
  6.   }
  7.   return mappedArr;
  8. }

這樣似乎沒啥問題,但是 這個map的手寫源碼 根本解釋不通上面返回[empty × 5]的現(xiàn)象。

我們可以看一下返回結(jié)果:

如圖所示,我的天,這不是坑人嗎!

那真正的map方法應(yīng)該死怎樣實(shí)現(xiàn)的呢?

我猜想它應(yīng)該會去遍歷每一項(xiàng),并且判斷當(dāng)前項(xiàng)是否為empty,是的話就不執(zhí)行里面的操作,「里面指的是for循環(huán)里面的代碼」

好的,問題來了,怎么判斷當(dāng)前項(xiàng)是empty?確實(shí)難倒我了,為此,我們?nèi)タ聪耺ap的真正源碼吧!

依照 ecma262 草案,實(shí)現(xiàn)的map的規(guī)范如下:

下面根據(jù)草案的規(guī)定一步步來模擬實(shí)現(xiàn)map函數(shù):

 
 
 
 
  1. Array.prototype.map = function(callbackFn, thisArg) {
  2.   // 處理數(shù)組類型異常
  3.   if (this === null || this === undefined) {
  4.     throw new TypeError("Cannot read property 'map' of null or undefined");
  5.   }
  6.   // 處理回調(diào)類型異常
  7.   if (Object.prototype.toString.call(callbackfn) != "[object Function]") {
  8.     throw new TypeError(callbackfn + ' is not a function')
  9.   }
  10.   // 草案中提到要先轉(zhuǎn)換為對象
  11.   let O = Object(this);
  12.   let T = thisArg;
  13.   
  14.   let len = O.length >>> 0;
  15.   let A = new Array(len);
  16.   for(let k = 0; k < len; k++) {
  17.     // 還記得原型鏈那一節(jié)提到的 in 嗎?in 表示在原型鏈查找
  18.     // 如果用 hasOwnProperty 是有問題的,它只能找私有屬性
  19.     if (k in O) {
  20.       let kValue = O[k];
  21.       // 依次傳入this, 當(dāng)前項(xiàng),當(dāng)前索引,整個數(shù)組
  22.       let mappedValue = callbackfn.call(T, KValue, k, O);
  23.       A[k] = mappedValue;
  24.     }
  25.   }
  26.   return A;
  27. ``}

這里解釋一下, length >>> 0, 字面意思是指"右移 0 位",但實(shí)際上是把前面的空位用0填充,這里的作用是保證len為數(shù)字且為整數(shù)。

舉幾個特例:

 
 
 
 
  1. null >>> 0  //0
  2. undefined >>> 0  //0
  3. void(0) >>> 0  //0
  4. function a (){};  a >>> 0  //0
  5. [] >>> 0  //0
  6. var a = {}; a >>> 0  //0
  7. 123123 >>> 0  //123123
  8. 45.2 >>> 0  //45
  9. 0 >>> 0  //0
  10. -0 >>> 0  //0
  11. -1 >>> 0  //4294967295
  12. -1212 >>> 0  //4294966084

總體實(shí)現(xiàn)起來并沒那么難,需要注意的就是使用 in 來進(jìn)行原型鏈查找。同時,如果沒有找到就不處理,能有效處理稀疏數(shù)組的情況。

最后給大家奉上V8源碼,參照源碼檢查一下,其實(shí)還是實(shí)現(xiàn)得很完整了。

 
 
 
 
  1. function ArrayMap(f, receiver) {
  2.   CHECK_OBJECT_COERCIBLE(this, "Array.prototype.map");
  3.   // Pull out the length so that modifications to the length in the
  4.   // loop will not affect the looping and side effects are visible.
  5.   var array = TO_OBJECT(this);
  6.   var length = TO_LENGTH(array.length);
  7.   if (!IS_CALLABLE(f)) throw %make_type_error(kCalledNonCallable, f);
  8.   var result = ArraySpeciesCreate(array, length);
  9.   for (var i = 0; i < length; i++) {
  10.     if (i in array) {
  11.       var element = array[i];
  12.       %CreateDataProperty(result, i, %_Call(f, receiver, element, i, array));
  13.     }
  14.   }
  15.   return result;
  16. }

我們可以看到?!钙鋵?shí)就是用key in array 的操作判斷當(dāng)前是否為empty?!?可不是嘛,key都沒有,當(dāng)然是empty了。

另外我們不能用var arrMap的方式去初始化一個即將返回的新數(shù)組,看源碼。發(fā)現(xiàn)是要通過new Array(len)的方式去初始化

所以我們這樣實(shí)現(xiàn)map方法 可以這樣去優(yōu)化

 
 
 
 
  1. Array.prototype.MyMap = function(fn, context){
  2.     var arr = Array.prototype.slice.call(this);;
  3.     var mapArr = new Array(this.length);
  4.     
  5.     for (var i = 0; i < arr.length; i++ ){
  6.      if (i in arr) {
  7.         mapArr.push(fn.call(context, arr[i], i, this));
  8.      }
  9.     }
  10.     return mapArr;
  11.   }

嘿嘿!感覺下一次面試遇到這個問題,我可以吹牛了!

為什么 key in Array 可以判斷 當(dāng)前項(xiàng)是否為 empty呢?

這個就要涉及到 一個對象的「常規(guī)屬性」和 「排序?qū)傩浴?/p>

由于以前我已經(jīng)寫過文章來解釋過 這兩個東西,我就不再贅述了,大家可以點(diǎn)擊這篇文章進(jìn)去看看,里面利用一道面試題講解了「常規(guī)屬性」和 「排序?qū)傩浴?/p>

百度前端面試題:for in 和 for of的區(qū)別詳解以及為for in的輸出順序

我們可以看到文章里面這張圖。是不是可以發(fā)現(xiàn) 2 in bar 是false的 因?yàn)?這個 為2的key 根本就不在 element上。

參考文章

【手寫數(shù)組的 map 方法 ?】http://47.98.159.95/my_blog/blogs/javascript/js-array/006.html

【這道JS筆試題你做對了嗎?】https://juejin.cn/post/6844904032507559944


分享題目:一道JS筆試題,刷新了我對map方法函數(shù)的認(rèn)知,你做對了嗎?
文章起源:http://www.dlmjj.cn/article/djighgs.html