一道JS筆試題, 刷新了我對map方法函數(shù)的認知,你做對了嗎?
背景
昨天在看一道筆試題的時候本以為很簡單,但是結(jié)果不是我想象的那樣,直接上筆試題。
- const array = new Array(5).map((item) => {
- return item = {
- name: '1'
- }
- });
- console.log(array);
- // 請寫出輸出結(jié)果
「我想象的答案」:[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];
「實際的答案」:[empty × 5]
為什么會這樣了?
猜想1
我第一個想到的是new Array(5)生成的數(shù)組是[undefined, undefined, undefined, undefined, undefined]。
- const array = [undefined, undefined, undefined, undefined, undefined];
- const newArr = array.map((item) => {
- return item = {
- name: '1'
- }
- });
- console.log(newArr);
- // 結(jié)果是[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];
「猜想1錯誤」
猜想2
new Array(5)生成的數(shù)組在每一項都沒有值,意思就是生成了[,,,,,]一個這樣的數(shù)組。
- const array = [,,,,,];
- const newArr = array.map((item) => {
- return item = {
- name: '1'
- }
- });
- console.log(newArr);
- // 結(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ù)組索引進行調(diào)用----。map函數(shù)的回調(diào)函數(shù)只會被賦過值的項調(diào)用。new Array(1) 和 [undefined]不一樣。new Array(1)沒有為數(shù)組中的項賦過值,而[undefined]為數(shù)組中的項賦了一個undefined值。
總結(jié)
new Array(5)產(chǎn)生的數(shù)組是一個沒有為數(shù)組中的項賦過值的數(shù)組。map僅對已分配值(包括)的數(shù)組索引進行callback調(diào)用。
對map方法的深入思考
- const array = new Array(5)
可以理解成
- const array = []
- array.length = 5
也可以理解
- const array = [,,,,,]
但是這里讓我產(chǎn)生一個疑問:
以前我學習 手寫map方法的時候
你百度一下,會發(fā)現(xiàn)也基本上很多人都是這樣手寫的:
- Array.prototype.MyMap = function(fn, context){
- var arr = Array.prototype.slice.call(this);//由于是ES5所以就不用...展開符了
- var mappedArr = [];
- for (var i = 0; i < arr.length; i++ ){
- mappedArr.push(fn.call(context, arr[i], i, this));
- }
- return mappedArr;
- }
這樣似乎沒啥問題,但是 這個map的手寫源碼 根本解釋不通上面返回[empty × 5]的現(xiàn)象。
我們可以看一下返回結(jié)果:

如圖所示,我的天,這不是坑人嗎!
那真正的map方法應該死怎樣實現(xiàn)的呢?
我猜想它應該會去遍歷每一項,并且判斷當前項是否為empty,是的話就不執(zhí)行里面的操作,「里面指的是for循環(huán)里面的代碼」
好的,問題來了,怎么判斷當前項是empty?確實難倒我了,為此,我們?nèi)タ聪耺ap的真正源碼吧!
依照 ecma262 草案,實現(xiàn)的map的規(guī)范如下:

下面根據(jù)草案的規(guī)定一步步來模擬實現(xiàn)map函數(shù):
- Array.prototype.map = function(callbackFn, thisArg) {
- // 處理數(shù)組類型異常
- if (this === null || this === undefined) {
- throw new TypeError("Cannot read property 'map' of null or undefined");
- }
- // 處理回調(diào)類型異常
- if (Object.prototype.toString.call(callbackfn) != "[object Function]") {
- throw new TypeError(callbackfn + ' is not a function')
- }
- // 草案中提到要先轉(zhuǎn)換為對象
- let O = Object(this);
- let T = thisArg;
- let len = O.length >>> 0;
- let A = new Array(len);
- for(let k = 0; k < len; k++) {
- // 還記得原型鏈那一節(jié)提到的 in 嗎?in 表示在原型鏈查找
- // 如果用 hasOwnProperty 是有問題的,它只能找私有屬性
- if (k in O) {
- let kValue = O[k];
- // 依次傳入this, 當前項,當前索引,整個數(shù)組
- let mappedValue = callbackfn.call(T, KValue, k, O);
- A[k] = mappedValue;
- }
- }
- return A;
- ``}
這里解釋一下, length >>> 0, 字面意思是指"右移 0 位",但實際上是把前面的空位用0填充,這里的作用是保證len為數(shù)字且為整數(shù)。
舉幾個特例:
- 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 //45
- 0 >>> 0 //0
- -0 >>> 0 //0
- -1 >>> 0 //4294967295
- -1212 >>> 0 //4294966084
總體實現(xiàn)起來并沒那么難,需要注意的就是使用 in 來進行原型鏈查找。同時,如果沒有找到就不處理,能有效處理稀疏數(shù)組的情況。
最后給大家奉上V8源碼,參照源碼檢查一下,其實還是實現(xiàn)得很完整了。
- 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;
- }
我們可以看到?!钙鋵嵕褪怯胟ey in array 的操作判斷當前是否為empty。」 可不是嘛,key都沒有,當然是empty了。
另外我們不能用var arrMap的方式去初始化一個即將返回的新數(shù)組,看源碼。發(fā)現(xiàn)是要通過new Array(len)的方式去初始化

所以我們這樣實現(xiàn)map方法 可以這樣去優(yōu)化
- 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; i++ ){
- if (i in arr) {
- mapArr.push(fn.call(context, arr[i], i, this));
- }
- }
- return mapArr;
- }
嘿嘿!感覺下一次面試遇到這個問題,我可以吹牛了!
為什么 key in Array 可以判斷 當前項是否為 empty呢?
這個就要涉及到 一個對象的「常規(guī)屬性」和 「排序?qū)傩浴?/p>
由于以前我已經(jīng)寫過文章來解釋過 這兩個東西,我就不再贅述了,大家可以點擊這篇文章進去看看,里面利用一道面試題講解了「常規(guī)屬性」和 「排序?qū)傩浴?/p>
百度前端面試題:for in 和 for of的區(qū)別詳解以及為for in的輸出順序

我們可以看到文章里面這張圖。是不是可以發(fā)現(xiàn) 2 in bar 是false的 因為 這個 為2的key 根本就不在 element上。
參考文章
【手寫數(shù)組的 map 方法 ?】http://47.98.159.95/my_blog/blogs/javascript/js-array/006.html
【這道JS筆試題你做對了嗎?】https://juejin.cn/post/6844904032507559944