1. 程式人生 > 實用技巧 >關於資料的遍歷方法

關於資料的遍歷方法

forEach
forEach遍歷完整,不會中斷,在其內部使用return也只是起到continue的作用,僅跳過當前這條
arr.forEach((item, index, arr1) => {
...
})

map

map 遍歷完整,不中斷,返回新陣列
const map1 = arr.map(x => x * 2); // 返回一個arr值的二倍陣列, [1,2,3] => [2,4,6]

filter

filter遍歷完整,不中斷,返回新陣列判斷是true作為新陣列的單元
const map1 = arr.map(x => x>2); // 返回一個arr值的二倍陣列, [1,2,3,5, 6, 7] => [3,5,6,7]

 

find

find找到第一個符合條件,中斷,返回一個值   , 沒找到就是undefined
const map1 = arr.find(x => x>2); // 返回一個值, [1,2,3,5, 6, 7] => 3

 

findIndex

find找到第一個符合條件,中斷,返回一個索引   , 沒找到就是undefined
const map1 = arr.findIndex(x => x>2); // 返回一個值, [1, 2, 3, 5, 6, 7] => 2

 

includes

includes 是否包含一個指定的值。它返回一個布林值true/false。
const map1 = arr.includes(3); // 是否含有3, [1,2,3,5, 6, 7] => true

some

some 找到第一個符合條件中斷。它返回一個布林值true/false。
const map1 = arr.map(x => x>2); // 是否含有大於2的值, [1,2,3,5, 6, 7] => true

 

every

every 遍歷完整,不中斷。它返回一個布林值true/false。
every 都符合條件,返回一個true;否則,返回一個false
const map1 = arr.map(x => x>2); // 是否都大於2, [1,2,3,5, 6, 7] => false

 

reduce

reduce 遍歷完整,不中斷。彙總為單個返回值

reducer函式接收4個引數:

  1. Accumulator (acc) (累計器)
  2. Current Value (cur) (當前值)
  3. Current Index (idx) (當前索引)
  4. Source Array (src) (源陣列)

const map1 = arr.reduce((acc, cur, idx, arr)=> {
  return acc + cur*idx
}); // 返回一個值, 第一個數不是成為cur,二是acc的初始值,cur的第一個值是第二個數