underscore.js源碼分析第三篇,前兩篇地址分別是javascript
本篇原文連接git
源碼地址github
😔看了不少篇技術文章,卻依然寫很差前端。api
從步入程序猿這個大坑開始到如今,已經看過數不清的技術文章和書籍,有的是零散的知識,有的是系列權威的教程,但爲毛還寫很差摯愛的前端,據說過一句話,這個世界又不是隻有你一我的深愛而不得。但縱使如此,我也要技術這條路上一路走到黑。直到天涯迷了路,海角翻了船。數組
今天想說幾個相似咱們日常的工做中常常用到的幾個寶貝,姑且把他叫作殺手鐗好了,由於實在是特別好用呀,他們分別是...ide
接下來咱們從下劃線underscore.js的視角,一步步看他們的內部運行的原理是什麼....函數
遍歷list中的全部元素,按順序用遍歷輸出每一個元素,若是傳遞了context,則將iteratee函數中的this綁定到context上。工具
先來看一下怎麼使用
let arr = ['name', 'sex']
let obj = {
name: 'qianlongo',
sex: 'boy'
}
// 不傳入context
// 遍歷數組
_.each(arr, console.log)
// name 0 (2) ["name", "sex"]
// sex 1 (2) ["name", "sex"]
// 遍歷對象
_.each(obj, console.log)
// qianlongo name {name: "qianlongo", sex: "boy"}
// boy sex {name: "qianlongo", sex: "boy"}
// 傳入context
_.each(arr, function (val, key, arr) {
console.log(this[val])
}, obj)
// qianlongo
// boy複製代碼
能夠看出下劃線的each和原生的數組forEach有些相似也有不一樣的地方
原生的forEach只能夠遍歷數組,而下劃線的each還能夠遍歷對象。接下來你想不想一塊兒看下下劃線是怎麼實現的。come on!!!
源碼
_.each = _.forEach = function(obj, iteratee, context) {
// 優化遍歷函數iteratee,將iteratee中的this動態設置爲context
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) { // 若是是類數組類型的obj
for (i = 0, length = obj.length; i < length; i++) {
// iteratee接收的三個參數分別是 數組的值,數組的索引,以及數組自己
iteratee(obj[i], i, obj);
}
} else { // 支持對象類型的數據迭代
var keys = _.keys(obj); // 拿到obj自身的全部keys
for (i = 0, length = keys.length; i < length; i++) {
// iteratee接收的三個參數分別是 obj的屬性值,obj的屬性,obj自己
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj; // 最後將obj返回
};複製代碼
😉,其實也沒有那麼難理解是吧!開始map函數之旅吧
經過iteratee將list中的每一個值映射到一個新的數組中(注:產生一個新的數組。y = f(x),相似高中學過的知識,將x經過f()映射爲一個新的數
使用案例
let arr = ['qianlongo', 'boy']
let obj = {
name: 'qianlongo',
sex: 'boy'
}
// list是個數組的時候
_.map(arr, (val, index) => {
return `hello : ${val}`
})
// ["hello : qianlongo", "hello : boy"]
// list是個對象的時候
_.map(obj, (val, key, obj) => {
return `hello : ${val}`
})
// ["hello : qianlongo", "hello : boy"]複製代碼
固然還能夠傳入第三個參數context,其本質如each通常,也是讓iteratee函數中的this動態設置爲context
源碼
_.map = _.collect = function(obj, iteratee, context) {
// 能夠將這裏的內部cb函數理解爲綁定iteratee的this到context
iteratee = cb(iteratee, context);
// 非類數組對象就獲取obj的keys,這裏若是是類數組最後獲得的keys爲undefined
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
results = Array(length); // 建立一個和obj長度空間同樣的數組
for (var index = 0; index < length; index++) {
// 注意這裏,keys存在則表明obj是個對象,因此要拿到keys中的值,不然是類數組的話,直接用index索引就行了
var currentKey = keys ? keys[index] : index;
// 看到了嗎,這裏將iteratee執行後的返回值塞到了results數組中
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results; // 最後將映射以後的數組返回
};複製代碼
經過源碼能夠看到map的實現思路
當list中的全部的元素均可以經過predicate的檢測,那麼結果返回true,不然false
使用案例
let arr = [-1, -3, -6, 0, 3, 6, 9]
let obj = {
name: 'qianlongo',
sex: 'boy'
}
let result = _.every(arr, (val, key, arr) => {
return val > 0
})
// false
let result2 = _.every(obj, (val, key, obj) => {
return val.indexOf('o') > -1
})
// true複製代碼
使用起來蠻簡單的,傳入一個謂詞函數(返回值是一個布爾值的函數),最後獲得true或者false。
源碼
_.every = _.all = function(obj, predicate, context) {
// 能夠將這裏的內部cb函數理解爲綁定iteratee的this到context
predicate = cb(predicate, context);
// 短路寫法,非類數組則獲取其keys
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
// keys若能轉化爲"真" 則說明obj是對象類型
var currentKey = keys ? keys[index] : index;
// 只要有一個不知足就返回false,中斷迭代
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true; // 不然全部元素都經過判斷返回true
};複製代碼
若是list中有任何一個元素經過 predicate的檢測就返回true。不然返回false,和every剛好有點相反的意思。
使用案例
let arr = [-1, -3, -6, 0, 3, 6, 9]
let obj = {
name: 'qianlongo',
sex: ''
}
let result = _.some(arr, (val, key, arr) => {
return val > 0
})
// true 由於至少有一個元素 >0
let result2 = _.some(obj, (val, key, obj) => {
return val.indexOf('o') > -1
})
// true 兩個都包含'o' 固然返回true複製代碼
源碼中是怎麼實現的呢,與every惟一不一樣的地方在返回true
仍是falase
之處?
源碼
_.some = _.any = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true; // 只要有一個知足條件就返回true
}
return false; // 全部都不知足則返回false
};複製代碼
遍歷list中的元素,返回第一個經過predicate函數檢測的值。
使用案例
let arr = [-1, -3, -6, 0, 3, 6, 9]
let obj = {
sex: 'boy',
name: 'qianlongo'
}
let result = _.find(arr, (val, key, arr) => {
return val > 0
})
// 3
let result2 = _.find(obj, (val, key, obj) => {
return val.indexOf('o') > -1
})
// boy複製代碼
源碼
_.find = _.detect = function(obj, predicate, context) {
var key;
if (isArrayLike(obj)) {
// 當傳入的是類數組的時候,調用findIndex方法,結果是>= -1的數組
key = _.findIndex(obj, predicate, context);
} else {
// 當傳入的是一個對象的時候,調用findKey,結果是一個字符串屬性或者undefined
key = _.findKey(obj, predicate, context);
}
// 返回符合條件的value,不然沒有返回值,即默認的undefined
if (key !== void 0 && key !== -1) return obj[key];
};複製代碼
_.findIndex
和_.findKey
在後面會一一分析,目前理解find函數知道他們怎麼用就好。
遍歷list,返回包含全部經過predicate檢測的元素(結果是個數組)
使用案例
let arr = [-1, -3, -6, 0, 3, 6, 9]
let obj = {
sex: 'boy',
name: 'qianlongo',
age: 100
}
let result = _.filter(arr, (val, key, arr) => {
return val > 0
})
// [3, 6, 9]
let result2 = _.filter(obj, (val, key, obj) => {
return `${val}`.indexOf('o') > -1 // 使用模板字符串是防止100沒有indexOf方法而報錯
})
// ["boy", "qianlongo"]複製代碼
聰明的你是否是已經想到了源碼是怎麼實現的了 😉
源碼
_.filter = _.select = function(obj, predicate, context) {
var results = [];
// 綁定predicate的this做用域到context
predicate = cb(predicate, context);
// 用each方法對obj進行遍歷
_.each(obj, function(value, index, list) {
// 符合predicate過濾條件的,就把對應的值塞到results數組中
if (predicate(value, index, list)) results.push(value);
});
return results; // 最後返回
};複製代碼
最後是reduce和reduceRight,兩個相對來講更難一些的api,雖然已通過了12點了,手動睏乏😪, 咱們咬咬牙堅持一下,把最後兩個說完
別名爲 inject 和 foldl, reduce方法把list中元素歸結爲一個單獨的數值。Memo是reduce函數的初始值,reduce的每一步都須要由iteratee返回。這個迭代傳遞4個參數:memo, value 和 迭代的index(或者 key)和最後一個引用的整個 list
reducRight是從右側開始組合的元素的reduce函數
使用案例
var arr = [0, 1, 2, 3, 4, 5],
sum = _.reduce(arr, (init, cur, i, arr) => {
return init + cur;
});
// 15複製代碼
咱們來看一下上面的執行過程是怎樣的。
第一回合
// 由於initialValue沒有傳入因此回調函數的第一個參數爲數組的第一項
init = 0;
cur = 1;
=> init + cur = 1;複製代碼
第二回合
init = 1;
cur = 2;
=> init + cur = 3;複製代碼
第三回合
init = 3;
cur = 3;
=> init + cur = 6;複製代碼
第四回合
init = 6;
cur = 4;
=> init + cur = 10;複製代碼
第五回合
init = 10;
cur = 5;
=> init + cur = 15;複製代碼
😭媽媽啊,終於執行完了,這麼多回合才結束,哪像人家格鬥高手瞬間就把太極大師整掛了
知道了一步步執行流程,咱們來看下源碼究竟是怎麼實現的。
源碼
// 源碼仍是經過調用createReduce生成的,因此主要是看createReduce這個函數
_.reduce = _.foldl = _.inject = createReduce(1);複製代碼
這尼瑪看起來好嚇人啊,不怕,咱們一點點來分析
function createReduce(dir) {
// Optimized iterator function as using arguments.length
// in the main function will deoptimize the, see #1991.
function iterator(obj, iteratee, memo, keys, index, length) { // 真正執行迭代的地方
for (; index >= 0 && index < length; index += dir) {
var currentKey = keys ? keys[index] : index; // 若是keys存在則認爲是obj形式的參數,因此讀取keys中的屬性值,不然類數組只須要讀取索引index便可
memo = iteratee(memo, obj[currentKey], currentKey, obj); // 接着就是執行外部傳入的回調了,並將結果賦值爲memo,也就是咱們最後要到的值
}
return memo;
}
return function(obj, iteratee, memo, context) {
iteratee = optimizeCb(iteratee, context, 4); // 首先綁定一下this做用域
var keys = !isArrayLike(obj) && _.keys(obj), // 若是不是類數組就讀取其keys
length = (keys || obj).length,
index = dir > 0 ? 0 : length - 1; // 默認開始迭代的位置,從左邊第一個開始仍是右邊第一個
// Determine the initial value if none is provided.
if (arguments.length < 3) { // 若是沒有傳入初始化值,則將第一個值(左邊第一個或者右邊第一個)做爲初始值
memo = obj[keys ? keys[index] : index];
index += dir; // 從索引爲1開始或者索引爲length - 2開始迭代
}
return iterator(obj, iteratee, memo, keys, index, length); // 接着開始進入自定義的迭代函數,請往上看
};
}複製代碼
夜深人靜,有點睏乏了。但願這篇文章對你們有點做用。若是對前幾篇源碼分析的文章感興趣,歡迎前往頂部地址查看
不介意的話,在文章開頭的源碼地址那裏點一個小星星吧😀
不介意的話,在文章開頭的源碼地址那裏點一個小星星吧😀
不介意的話,在文章開頭的源碼地址那裏點一個小星星吧😀