成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

幫你精通JS:函數式array邏輯判斷的7個高階函數

開發 前端
JavaScript是當今流行語言中對函數式編程支持最好的編程語言。我們繼續構建函數式編程的基礎,在前文中分解介紹了對array數組作變形transform四種方法.

[[387420]]

 JavaScript是當今流行語言中對函數式編程支持最好的編程語言。我們繼續構建函數式編程的基礎,在前文中分解介紹了對array數組作變形transform四種方法,分別為:

  • array.reduce 幫你精通JS:神奇的array.reduce方法的10個案例
  • array.map 幫你精通JS:神奇的array.map的6個案例
  • array.flat and array.flatMap 幫你精通JS: array.flat與flatMap用法指南

為什么一種編程語言要耗費如此巨大的精力在數組這種數據結構上呢?因為數組是我們日常思考的基石。比如你早起籌劃的一天的任務是數組,你的購物清單是數組。

學習編程,絕不能將紙上的字符簡簡單單的只當作抽象的無意義的符號,我們要還原為,具象為具體的生活與應用之中。

接下來,我們繼續構建我們的思維。介紹用于邏輯判斷的array.filter, array.find, array.findIndex以及array.include(array.find應用于具體個例)和array.indexOf(array.findInde用于具體個例) 和array.some, array.every.

1.1 array.filter() 概述

filter() 方法創建一個新數組, 其包含通過所提供函數實現的測試的所有元素。

語法

  1. var newArray = arr.filter(callback(element[, index[, array]])[, thisArg]) 

參數

callback 用來測試數組的每個元素的函數。返回 true 表示該元素通過測試,保留該元素,false 則不保留。它接受以下三個參數:

- element 數組中當前正在處理的元素。

- index可選 正在處理的元素在數組中的索引。

- array可選 調用了 filter 的數組本身。

thisArg可選 執行 callback 時,用于 this 的值。

返回值

一個新的、由通過測試的元素組成的數組,如果沒有任何數組元素通過測試,則返回空數組。

1.2 array.filter() 描述

filter 為數組中的每個元素調用一次 callback 函數,并利用所有使得 callback 返回 true 或等價于 true 的值的元素創建一個新數組。callback 只會在已經賦值的索引上被調用,對于那些已經被刪除或者從未被賦值的索引不會被調用。那些沒有通過 callback 測試的元素會被跳過,不會被包含在新數組中。

callback 被調用時傳入三個參數:

  1. 元素的值
  2. 元素的索引
  3. 被遍歷的數組本身

如果為 filter 提供一個 thisArg 參數,則它會被作為 callback 被調用時的 this 值。否則,callback 的 this 值在非嚴格模式下將是全局對象,嚴格模式下為 undefined。callback 函數最終觀察到的 this 值是根據通常函數所看到的 "this"的規則確定的。

filter 不會改變原數組,它返回過濾后的新數組。

filter 遍歷的元素范圍在第一次調用 callback 之前就已經確定了。在調用 filter 之后被添加到數組中的元素不會被 filter 遍歷到。如果已經存在的元素被改變了,則他們傳入 callback 的值是 filter 遍歷到它們那一刻的值。被刪除或從來未被賦值的元素不會被遍歷到。

案例 01 篩選排除所有較小的值

下例使用 filter 創建了一個新數組,該數組的元素由原數組中值大于 10 的元素組成。

  1. function isBigEnough(element) { 
  2.   return element >= 10; 
  3. var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); 
  4. // filtered is [12, 130, 44] 

 案例 02 過濾 JSON 中的無效條目

以下示例使用 filter() 創建具有非零 id 的元素的 json。

  1. var arr = [ 
  2.   { id: 15 }, 
  3.   { id: -1 }, 
  4.   { id: 0 }, 
  5.   { id: 3 }, 
  6.   { id: 12.2 }, 
  7.   { }, 
  8.   { id: null }, 
  9.   { id: NaN }, 
  10.   { id: 'undefined' } 
  11. ]; 
  12.  
  13. var invalidEntries = 0; 
  14.  
  15. function isNumber(obj) { 
  16.   return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj); 
  17.  
  18. function filterByID(item) { 
  19.   if (isNumber(item.id) && item.id !== 0) { 
  20.     return true
  21.   } 
  22.   invalidEntries++; 
  23.   return false
  24.  
  25. var arrByID = arr.filter(filterByID); 
  26.  
  27. console.log('Filtered Array\n', arrByID); 
  28. // Filtered Array 
  29. // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }] 
  30.  
  31. console.log('Number of Invalid Entries = ', invalidEntries); 
  32. // Number of Invalid Entries = 5 

 案例 03 在數組中搜索

下例使用 filter() 根據搜索條件來過濾數組內容。

  1. var fruits = ['apple''banana''grapes''mango''orange']; 
  2.  
  3. /** 
  4.  * Array filters items based on search criteria (query) 
  5.  */ 
  6. function filterItems(query) { 
  7.   return fruits.filter(function(el) { 
  8.       return el.toLowerCase().indexOf(query.toLowerCase()) > -1; 
  9.   }) 
  10.  
  11. console.log(filterItems('ap')); // ['apple''grapes'
  12. console.log(filterItems('an')); // ['banana''mango''orange'

 案例 04 ES2015 實現

  1. const fruits = ['apple''banana''grapes''mango''orange']; 
  2.  
  3. /** 
  4.  * Array filters items based on search criteria (query) 
  5.  */ 
  6. const filterItems = (query) => { 
  7.   return fruits.filter((el) => 
  8.     el.toLowerCase().indexOf(query.toLowerCase()) > -1 
  9.   ); 
  10.  
  11. console.log(filterItems('ap')); // ['apple''grapes'
  12. console.log(filterItems('an')); // ['banana''mango', 'orang 

 2.1 array.find() 概述

find() 方法返回數組中滿足提供的測試函數的第一個元素的值。否則返回 undefined。

  1. const array1 = [5, 12, 8, 130, 44]; 
  2.  
  3. const found = array1.find(element => element > 10); 
  4.  
  5. console.log(found); 
  6. // expected output: 12 

 另請參見 3.1 findIndex() 方法,它返回數組中找到的元素的索引,而不是其值。

如果你需要找到一個元素的位置或者一個元素是否存在于數組中,使用Array.prototype.indexOf() 或 Array.prototype.includes()。

語法

  1. arr.find(callback[, thisArg]) 

參數

callback 在數組每一項上執行的函數,接收 3 個參數:

  • element 當前遍歷到的元素。
  • index可選 當前遍歷到的索引。
  • array可選 數組本身。

thisArg可選 執行回調時用作this 的對象。

返回值

數組中第一個滿足所提供測試函數的元素的值,否則返回 undefined。

2.2 array.find() 描述

find方法對數組中的每一項元素執行一次 callback 函數,直至有一個 callback 返回 true。當找到了這樣一個元素后,該方法會立即返回這個元素的值,否則返回 undefined。注意 callback 函數會為數組中的每個索引調用即從 0 到 length - 1,而不僅僅是那些被賦值的索引,這意味著對于稀疏數組來說,該方法的效率要低于那些只遍歷有值的索引的方法。

callback函數帶有3個參數:當前元素的值、當前元素的索引,以及數組本身。

如果提供了 thisArg參數,那么它將作為每次 callback函數執行時的this ,如果未提供,則使用 undefined。

find方法不會改變數組。

在第一次調用 callback函數時會確定元素的索引范圍,因此在 find方法開始執行之后添加到數組的新元素將不會被 callback函數訪問到。如果數組中一個尚未被callback函數訪問到的元素的值被callback函數所改變,那么當callback函數訪問到它時,它的值是將是根據它在數組中的索引所訪問到的當前值。被刪除的元素仍舊會被訪問到,但是其值已經是undefined了。

案例 01 用對象的屬性查找數組里的對象

  1. var inventory = [ 
  2.     {name'apples', quantity: 2}, 
  3.     {name'bananas', quantity: 0}, 
  4.     {name'cherries', quantity: 5} 
  5. ]; 
  6.  
  7. function findCherries(fruit) { 
  8.     return fruit.name === 'cherries'
  9.  
  10. console.log(inventory.find(findCherries)); // { name'cherries', quantity: 5 } 

 案例 02 尋找數組中的質數

下面的例子展示了如何從一個數組中尋找質數(如果找不到質數則返回undefined)

  1. function isPrime(element, index, array) { 
  2.   var start = 2; 
  3.   while (start <= Math.sqrt(element)) { 
  4.     if (element % start++ < 1) { 
  5.       return false
  6.     } 
  7.   } 
  8.   return element > 1; 
  9.  
  10. console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found 
  11. console.log([4, 5, 8, 12].find(isPrime)); // 5 

 當在回調中刪除數組中的一個值時,當訪問到這個位置時,其傳入的值是 undefined:

  1. // Declare array with no element at index 2, 3 and 4 
  2. var a = [0,1,,,,5,6]; 
  3.  
  4. // Shows all indexes, not just those that have been assigned values 
  5. a.find(function(value, index) { 
  6.   console.log('Visited index ' + index + ' with value ' + value); 
  7. }); 
  8.  
  9. // Shows all indexes, including deleted 
  10. a.find(function(value, index) { 
  11.  
  12.   // Delete element 5 on first iteration 
  13.   if (index == 0) { 
  14.     console.log('Deleting a[5] with value ' + a[5]); 
  15.     delete a[5];  // 注:這里只是將a[5]設置為undefined,可以試試用a.pop()刪除最后一項,依然會遍歷到被刪的那一項 
  16.   } 
  17.   // Element 5 is still visited even though deleted 
  18.   console.log('Visited index ' + index + ' with value ' + value); 
  19. }); 

 3.1 array.findIndex() 概述

findIndex()方法返回數組中滿足提供的測試函數的第一個元素的索引。若沒有找到對應元素則返回-1。

  1. var inventory = [ 
  2.     {name'apples', quantity: 2}, 
  3.     {name'bananas', quantity: 0}, 
  4.     {name'cherries', quantity: 5} 
  5. ]; 
  6.  
  7. function findCherries(fruit) { 
  8.     return fruit.name === 'cherries'
  9.  
  10. console.log(inventory.find(findCherries)); // { name'cherries', quantity: 5 } 

 另請參見 1.1 find() 方法,它返回數組中找到的元素的值,而不是其索引。

語法

  1. arr.findIndex(callback[, thisArg]) 

參數

callback 針對數組中的每個元素, 都會執行該回調函數, 執行時會自動傳入下面三個參數:

- element 當前元素。

- index 當前元素的索引。

- array 調用findIndex的數組。

thisArg 可選。執行callback時作為this對象的值.

返回值

數組中通過提供測試函數的第一個元素的索引。否則,返回-1

3.2 array.findIndex() 描述

findIndex方法對數組中的每個數組索引0..length-1(包括)執行一次callback函數,直到找到一個callback函數返回真實值(強制為true)的值。如果找到這樣的元素,findIndex會立即返回該元素的索引。如果回調從不返回真值,或者數組的length為0,則findIndex返回-1。 與某些其他數組方法(如Array#some)不同,在稀疏數組中,即使對于數組中不存在的條目的索引也會調用回調函數。

回調函數調用時有三個參數:元素的值,元素的索引,以及被遍歷的數組。

如果一個 thisArg 參數被提供給 findIndex, 它將會被當作this使用在每次回調函數被調用的時候。如果沒有被提供,將會使用undefined。

findIndex不會修改所調用的數組。

在第一次調用callback函數時會確定元素的索引范圍,因此在findIndex方法開始執行之后添加到數組的新元素將不會被callback函數訪問到。如果數組中一個尚未被callback函數訪問到的元素的值被callback函數所改變,那么當callback函數訪問到它時,它的值是將是根據它在數組中的索引所訪問到的當前值。被刪除的元素仍然會被訪問到。

案例 01 查找數組中首個質數元素的索引

以下示例查找數組中素數的元素的索引(如果不存在素數,則返回-1)。

  1. function isPrime(element, index, array) { 
  2.   var start = 2; 
  3.   while (start <= Math.sqrt(element)) { 
  4.     if (element % start++ < 1) { 
  5.       return false
  6.     } 
  7.   } 
  8.   return element > 1; 
  9.  
  10. console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found 
  11. console.log([4, 5, 8, 12].find(isPrime)); // 5 

 4.1 array.includes() 概述

當2.1的array.find查找具體的元素的時候,就是array.include。

includes() 方法用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則返回 true,否則返回false。

語法

  1. arr.includes(valueToFind[, fromIndex]) 

參數

valueToFind

需要查找的元素值。

Note: 使用 includes()比較字符串和字符時是區分大小寫。

fromIndex 可選 從fromIndex 索引處開始查找 valueToFind。如果為負值,則按升序從 array.length + fromIndex 的索引開始搜 (即使從末尾開始往前跳 fromIndex 的絕對值個索引,然后往后搜尋)。默認為 0。

返回值

返回一個布爾值 Boolean ,如果在數組中找到了(如果傳入了 fromIndex ,表示在 fromIndex 指定的索引范圍中找到了)則返回 true 。

案例 00 簡單示例

  1. [1, 2, 3].includes(2);     // true 
  2. [1, 2, 3].includes(4);     // false 
  3. [1, 2, 3].includes(3, 3);  // false 
  4. [1, 2, 3].includes(3, -1); // true 
  5. [1, 2, NaN].includes(NaN); // true 

 案例 01 fromIndex 大于等于數組長度

如果 fromIndex 大于等于數組的長度,則會返回 false,且該數組不會被搜索。

  1. var arr = ['a''b''c']; 
  2.  
  3. arr.includes('c', 3);   // false 
  4. arr.includes('c', 100); // false 

 案例 02 計算出的索引小于 0

如果 fromIndex 為負值,計算出的索引將作為開始搜索searchElement的位置。如果計算出的索引小于 0,則整個數組都會被搜索。

  1. // array length is 3 
  2. // fromIndex is -100 
  3. // computed index is 3 + (-100) = -97 
  4.  
  5. var arr = ['a''b''c']; 
  6.  
  7. arr.includes('a', -100); // true 
  8. arr.includes('b', -100); // true 
  9. arr.includes('c', -100); // true 
  10. arr.includes('a', -2); // false 

 案例 03 作為通用方法的 includes()

includes() 方法有意設計為通用方法。它不要求this值是數組對象,所以它可以被用于其他類型的對象 (比如類數組對象)。下面的例子展示了 在函數的 arguments 對象上調用的 includes() 方法。

  1. (function() { 
  2.   console.log([].includes.call(arguments, 'a')); // true 
  3.   console.log([].includes.call(arguments, 'd')); // false 
  4. })('a','b','c'); 

 5.1 array.indexOf() 概述

indexOf()方法返回在數組中可以找到一個給定元素的第一個索引,如果不存在,則返回-1。

語法

  1. arr.indexOf(searchElement[, fromIndex]) 

參數

  • searchElement

要查找的元素

  • fromIndex 可選

開始查找的位置。如果該索引值大于或等于數組長度,意味著不會在數組里查找,返回-1。如果參數中提供的索引值是一個負值,則將其作為數組末尾的一個抵消,即-1表示從最后一個元素開始查找,-2表示從倒數第二個元素開始查找 ,以此類推。 注意:如果參數中提供的索引值是一個負值,并不改變其查找順序,查找順序仍然是從前向后查詢數組。如果抵消后的索引值仍小于0,則整個數組都將會被查詢。其默認值為0.

返回值

首個被找到的元素在數組中的索引位置; 若沒有找到則返回 -1

5.2 array.indexOf() 描述

indexOf 使用strict equality (無論是 ===, 還是 triple-equals操作符都基于同樣的方法)進行判斷 searchElement與數組中包含的元素之間的關系。

案例 01 使用indexOf

以下例子使用indexOf方法確定多個值在數組中的位置。

  1. var array = [2, 5, 9]; 
  2. array.indexOf(2);     // 0 
  3. array.indexOf(7);     // -1 
  4. array.indexOf(9, 2);  // 2 
  5. array.indexOf(2, -1); // -1 
  6. array.indexOf(2, -3); // 0 

 案例 02 找出指定元素出現的所有位置

  1. var indices = []; 
  2. var array = ['a''b''a''c''a''d']; 
  3. var element = 'a'
  4. var idx = array.indexOf(element); 
  5. while (idx != -1) { 
  6.   indices.push(idx); 
  7.   idx = array.indexOf(element, idx + 1); 
  8. console.log(indices); 
  9. // [0, 2, 4] 

 案例 03 判斷一個元素是否在數組里,不在則更新數組

  1. function updateVegetablesCollection (veggies, veggie) { 
  2.     if (veggies.indexOf(veggie) === -1) { 
  3.         veggies.push(veggie); 
  4.         console.log('New veggies collection is : ' + veggies); 
  5.     } else if (veggies.indexOf(veggie) > -1) { 
  6.         console.log(veggie + ' already exists in the veggies collection.'); 
  7.     } 
  8.  
  9. var veggies = ['potato''tomato''chillies''green-pepper']; 
  10.  
  11. // New veggies collection is : potato,tomato,chillies,green-papper,spinach 
  12. updateVegetablesCollection(veggies, 'spinach'); 
  13. // spinach already exists in the veggies collection. 
  14. updateVegetablesCollection(veggies, 'spinach');  

 6.總結

以上介紹了array用作高階邏輯判斷的5個函數:

array.filter, array.find, array,findIndex, array.includes, array.indexOf

另外還有比較常用但是較為簡單的array.every與array.some也用作邏輯判斷,此處略去不提。

 

責任編輯:姜華 來源: 今日頭條
相關推薦

2021-03-12 08:21:54

JavaScript 前端原生js

2021-03-17 06:03:41

函數式編程JavaScriptarray.filte

2021-03-05 07:45:59

JSreducemap

2021-04-08 09:14:24

js前端函數

2024-07-18 15:08:27

2023-05-06 07:27:47

2024-06-26 13:11:40

2021-09-08 08:55:45

Javascript 高階函數前端

2010-08-03 08:54:07

JDK 7Lambda表達式函數式編程

2015-03-18 09:39:10

函數編程Swift

2024-09-23 09:00:00

裝飾器函數代碼

2021-04-07 08:03:51

js舉起Hoisting初始化

2010-01-28 14:51:24

Scala后函數式

2020-11-09 07:25:20

函數 JavaScript數據

2024-05-13 18:33:08

SQL日期函數

2017-01-22 21:13:48

Android移動開發高階函數

2016-10-11 13:32:50

函數式TypeScriptJavascript

2020-12-17 08:14:30

Linuxrsync備份

2010-09-09 13:26:52

SQL函數判斷

2012-03-14 10:09:51

ibmdw
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 中文字幕精品一区二区三区精品 | 国产九一精品 | 九色网址| 欧美精品久久久 | 精品欧美一区二区三区久久久 | 综合二区 | 中文字幕的av | 中文日韩在线视频 | 色吊丝2288sds中文字幕 | 久久久久久九九九九九九 | 久久免费精品 | 国产精品免费观看 | 久久精品高清视频 | 91久久精品国产91久久性色tv | 久久99深爱久久99精品 | 成人黄页在线观看 | 亚洲福利一区二区 | 一区二区三区四区av | 欧美激情一区二区三级高清视频 | 伊人狠狠干 | 夜久久 | 一二三区在线 | 黄网站免费在线看 | 国产成人精品一区二区三区在线观看 | 国产精品视频一 | 亚洲欧美视频一区 | 人人九九精 | 国产中文字幕在线观看 | 99免费精品视频 | 久久久久久亚洲 | 欧美一区二区三区 | 亚洲国产精品久久久久婷婷老年 | 日本精品一区二区 | www.日日操 | 中文字幕亚洲精品在线观看 | 天天色综 | 国产一区不卡 | 成人欧美一区二区三区在线观看 | 手机看黄av免费网址 | 午夜天堂精品久久久久 | 午夜影院在线观看 |