本系列使用 lodash 4.17.4版本數組
此方法沒有對其餘方法進行引用源碼分析
/**
* The inverse of `toPairs`is method returns an object composed
* from key-value `pairs`.
*
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* fromPairs([['a', 1], ['b', 2]])
* // => { 'a': 1, 'b': 2 }
*/
function fromPairs(pairs) {
const result = {}
if (pairs == null) {
return result
}
for (const pair of pairs) {
result[pair[0]] = pair[1]
}
return result
}
export default fromPairs
複製代碼
該方法接受一個將被轉換爲對象的二維數組。post
該方法返回一個對象。spa
1.該方法會首先定義一個result
空對象。code
2.該方法會判斷傳入的參數是否爲空數組,若爲空數組則會直接將result
空對象返回給調用該方法的地方;若不爲空繼續下一步。對象
3.該方法會對傳入的二維數組進行遍歷操做,在遍歷中,將二維數組下的每一個一維數組的第一項轉換爲字符串做爲對象的屬性,第二項做爲對象的屬性值,組成一對鍵值對賦給以前定義的result
對象。遍歷操做結束後,將result
對象返回給該方法調用的地方。rem
注: 該方法沒有對傳入的參數進行類型判斷。字符串
null
和undefined
時會被視爲空數組或空變量而直接將空對象result
返回給調用的地方;undefine: undefined
鍵值對賦值給對象;undefined
做爲屬性值賦值給對象;注: 當傳入的二維數組下的一維數組值不足兩個,不足的會以undefined
代替,超過兩個的會被無視。get
注: 當傳入的二維數組下的一維數組值不足兩項時,不足的項會以undefined
代替,超過兩項的項會被無視。源碼
fromPairs([[3, 1], [6, 5]]);
--> {'3': 1, '6': 5}
fromPairs([[5, 3, 6], [2]])
--> {2: undefined, 5: 3}
fromPairs([[[5, 3, 6], [2]], [[2, 7], [1, 8]]])
--> {5,3,6: Array(1), 2,7: Array(2)}
fromPairs("DrMoon");
--> {D: undefined, r: undefined, M: undefined, o: undefined, n: undefined}
fromPairs(5);
--> Uncaught TypeError: pairs is not iterable
fromPairs(true);
--> Uncaught TypeError: pairs is not iterable
fromPairs(null);
--> null
fromPairs(undefined);
--> undefined
複製代碼
該方法會將傳入的二維數組轉換爲一個對象,二維數組下每一個一維數組的前兩項組成一對鍵值對做爲對象的屬性與屬性值。
每日源碼分析 - lodash(debounce.js和throttle.js)
本文章來源於午安煎餅計劃Web組 - 殘陽