這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 背景 昨天在看一道筆試題的時候本以為很簡單,但是結果不是我想象的那樣,直接上筆試題。 const array = new Array(5).map((item) => { return item = { name: '1' } }); c ...
這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助
背景
昨天在看一道筆試題的時候本以為很簡單,但是結果不是我想象的那樣,直接上筆試題。
const array = new Array(5).map((item) => { return item = { name: '1' } }); console.log(array); // 請寫出輸出結果
我想象的答案:[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}]
;
實際的答案:[empty × 5]
為什麼會這樣了?
猜想1
我第一個想到的是new Array(5)生成的數組是[undefined, undefined, undefined, undefined, undefined]
。
const array = [undefined, undefined, undefined, undefined, undefined]; const newArr = array.map((item) => { return item = { name: '1' } }); console.log(newArr); // 結果是[{name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}, {name: '1'}];
猜想1錯誤
猜想2
new Array(5)生成的數組在每一項都沒有值,意思就是生成了[,,,,,]一個這樣的數組。
const array = [,,,,,]; const newArr = array.map((item) => { return item = { name: '1' } }); console.log(newArr); // 結果是[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依次為數組中的每個元素調用一次提供的callback函數,然後根據結果構造一個新的數組。-----僅對已分配值(包括)的數組索引進行調用----。 map函數的回調函數只會被賦過值的項調用。new Array(1) 和 [undefined]
不一樣。new Array(1)沒有為數組中的項賦過值,而[undefined]
為數組中的項賦了一個undefined值。 總結
new Array(5)產生的數組是一個沒有為數組中的項賦過值的數組。 map僅對已分配值(包括)的數組索引進行callback調用。
對map方法的深入思考
const array = new Array(5)
可以理解成
const array = [] array.length = 5
也可以理解
const array = [,,,,,]
但是這裡讓我產生一個疑問:
以前我學習 手寫map方法的時候
你百度一下,會發現也基本上很多人都是這樣手寫的:
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]
的現象。
我們可以看一下返回結果:
如圖所示,我的天,這不是坑人嗎!
那真正的map方法應該死怎樣實現的呢?
我猜想它應該會去遍歷每一項,並且判斷當前項是否為empty,是的話就不執行裡面的操作,裡面指的是for迴圈裡面的代碼
好的,問題來了,怎麼判斷當前項是empty?確實難倒我了,為此,我們去看下map的真正源碼吧!
依照 ecma262 草案,實現的map的規範如下:
下麵根據草案的規定一步步來模擬實現map函數:
Array.prototype.map = function(callbackFn, thisArg) { // 處理數組類型異常 if (this === null || this === undefined) { throw new TypeError("Cannot read property 'map' of null or undefined"); } // 處理回調類型異常 if (Object.prototype.toString.call(callbackfn) != "[object Function]") { throw new TypeError(callbackfn + ' is not a function') } // 草案中提到要先轉換為對象 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, 字面意思是指"右移 0 位",但實際上是把前面的空位用0填充,這裡的作用是保證len為數字且為整數。
舉幾個特例:
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
總體實現起來並沒那麼難,需要註意的就是使用 in 來進行原型鏈查找。同時,如果沒有找到就不處理,能有效處理稀疏數組的情況。
最後給大家奉上V8源碼,參照源碼檢查一下,其實還是實現得很完整了。
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)的方式去初始化
所以我們這樣實現map方法 可以這樣去優化
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呢?
這個就要涉及到 一個對象的常規屬性和 排序屬性
由於以前我已經寫過文章來解釋過 這兩個東西,我就不再贅述了,大家可以點擊這篇文章進去看看,裡面利用一道面試題講解了常規屬性和 排序屬性
百度前端面試題:for in 和 for of的區別詳解以及為for in的輸出順序
我們可以看到文章裡面這張圖。是不是可以發現 2 in bar 是false的 因為 這個 為2的key 根本就不在 element上。
好家伙,又可以跟面試官吹牛逼了!