JavaScript數組(遍歷)方法

Array.forEach()
  • 爲每個數組元素調用一次函數(回調函數)。
  • 會自己改變原數組
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
Array.map()
  • 通過對每個數組元素執行函數來創建新數組
  • 不會對沒有值的數組元素執行函數。
  • 不會更改原始數組。
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
Array.reduce(),Array.reduceRight()
  • 方法接收一個函數作爲累加器,數組中的每個值(從左到右)開始縮減,最終計算爲一個值。
  • 方法不會減少原始數組。
  • reduceRight與reduce類似,不同之處在於它是從最後一個值開始計算的。
// 參數:
// Accumulator (acc) (累計器)
// Current Value (cur) (當前值)
// Current Index (idx) (當前索引)
// Source Array (src) (源數組)

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.every()
  • 方法測試一個數組內的所有元素是否都能通過某個指定函數的測試。它返回一個布爾值。
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true

Array.some()
  • 方法測試數組中是不是至少有1個元素通過了被提供的函數測試。它返回的是一個Boolean類型的值。
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true
Array.indexOf()
  • 方法返回在數組中可以找到一個給定元素的第一個索引,如果不存在,則返回-1。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1
Array.find()
  • 方法返回數組中滿足提供的測試函數的第一個元素的值。否則返回 undefined。
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12
Array.filter()
  • 方法創建一個新數組, 其包含通過所提供函數實現的測試的所有元素。
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Array.includes()
  • 方法用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則返回 true,否則返回false。
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章