初探 Iterator.every()
前言
在之前的 初探 Iterator.take() 介紹 Iterator.take() ,這次學習 Iterator.every() ,在此把學習的過程做個紀錄。
內容
範例如下
function* count(){
let curNum = 0;
while(true){
console.log( curNum );
yield curNum++;
}
}
//
const isLessThree = ( num ) => num < 3 ;
let conItor = count();
console.log( conItor.every(isLessThree) );
// 0
// 1
// 2
// 3
// false
//
console.log( count().take(2).every( isLessThree ) );
// 0
// 1
// true
//
console.log( count().take(5).every( isLessThree ) );
// 0
// 1
// 2
// 3
// false
Iterator.every() 的引數需要一個 Function , Function 需要回傳 True 或 False ,該 Function 的引數會是每次 yield 的回傳。Iterator.every() 在喚起後會在每次 yield 後喚起給予的 Function ,以範例來說就是 isLessThree() ,如果 isLessThree() 的回傳值是 true ,那就會去取得下一次的 yield ,回傳值為 false , Iterator.every() 就不再取得 yield ,結束執行, Iterator.every() 還會有回傳值,意義是每次喚起 Funciton 的過程中是否有回傳過 False ,如果都沒回傳過就會是 True ,這次範例的 count() 會在每次 yield 列印數值,這是為了方便看每次的Iterator.every() 計數的狀況。範例第一次喚起 Iterator.every() 後,救計數到 3 後回傳 False ,接著搭配 Iterator.take() 來使用 ,Iterator.take() 的參數是 2 ,所以可以看到結果只計數到 2 ,由於整個過程都沒回傳過 False ,所以回傳結果是 True ,最後 Iterator.take() 的參數是 5 ,但會發現還是只計數到 3 ,並不會計數到 5 ,黨然回傳的結果會是 False。
參考資料
[ developer.mozilla.org ] Iterator.prototype.every()