Javascript迭代器

It’s hit me like a heart attack.

Walle
漫築蘭格
5 min readMar 31, 2019

--

以下解釋皆參考自卡斯伯,範例則是我自己隨便找喜歡的~

Array.prototype.filter()

filter() 會回傳一個新的陣列到指定變數裡,其條件是 return 後方為 true 的物件,很適合用在搜尋符合條件的資料。

const words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

let longWords = words.filter(word => word.length > 6);

// Filtered array longWords is ["exuberant", "destruction", "present"]

Array.prototype.find()

find() 與 filter() 很像,但 find() 只會回傳一次值,且是第一次為 true 的值。

function isPrime(element, index, array) {   //找質數
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5

Array.prototype.forEach()

forEach 是這幾個陣列函式最單純的一個,不會額外回傳值,只單純執行每個陣列內的物件或值。

const items = ['item1', 'item2', 'item3'];
const copy = [];

items.forEach(function(item){
copy.push(item)
}); //copy = ['item1', 'item2', 'item3']

Array.prototype.map()

使用 map() 時他需要回傳一個值,他會透過函式將回傳的值組合成新的陣列

  • 如果不回傳則是 undefined
  • 回傳數量等於原始陣列的長度

這很適合將原始的變數運算後重新組合一個新的陣列。

var array1 = [1, 4, 9, 16];// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
-------------------------------------------------
const numbers = [1, 4, 9];
let roots = numbers.map(Math.sqrt); //map會return一個新的array
// roots 現在是 [1, 2, 3]

Array.prototype.every()

every() 可以檢查所有的陣列是否符合條件,這僅會回傳一個值 true or false

function isBelowThreshold(currentValue) {
return currentValue < 40;
}
var array1 = [1, 30, 39, 29, 10, 13];console.log(array1.every(isBelowThreshold));
// expected output: true

Array.prototype.some()

some() 與 every() 非常接近,都是回傳 true or false,差異僅在 every() 需完全符合,some() 僅需要部分符合

[2, 5, 8, 1, 4].some(x => x > 10);  // false
[12, 5, 8, 1, 4].some(x => x > 10); // true

Array.prototype.reduce()

reduce() 可以與前一個回傳的值再次作運算,參數包含以下:

  • accumulator: 前一個參數,如果是第一個陣列的話,值是以另外傳入或初始化的值
  • currentValue: 當前變數
  • currentIndex: 當前索引
  • array: 全部陣列
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue ;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Array.prototype.keys()

keys() 方法會回傳一個包含陣列中的每一個索引(keys)的新 Array Iterator 物件。

var array1 = ['a', 'b', 'c'];
var iterator = array1.keys();

for (let key of iterator) {
console.log(key); // expected output: 0 1 2
}

--

--