JS數組的迭代

forEach

forEach() 方法對數組的每一個元素執行一次提供的函數。數組

var array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
  console.log(element);
});

// expected output: "a"
// expected output: "b"
// expected output: "c"

forEach()是沒有辦法停止或者跳出循環的,除非拋出一個異常。函數

map

map() 方法建立一個新數組,其結果是該數組中的每一個元素都調用一個提供的函數後返回的結果。測試

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]

map()與forEach()的區別是map返回一個循環處理後的數組,不改變原數組的值,而forEach則只是遍歷一遍數組,執行提供的函數。code

for of

for...of語句在可迭代對象(包括 Array,Map,Set,String,TypedArray,arguments 對象等等)上建立一個迭代循環,調用自定義迭代鉤子,併爲每一個不一樣屬性的值執行語句對象

let iterable = [10, 20, 30];

for (const value of iterable) {
  console.log(value);
}
// 10
// 20
// 30

關於for...of語句遍歷更多用法mdnip

filter

filter() 方法建立一個新數組, 其包含經過所提供函數實現的測試的全部元素。element

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

reduce

reduce() 方法對數組中的每一個元素執行一個由您提供的reducer函數(升序執行),將其結果彙總爲單個返回值。get

const array1 = [1, 2, 3, 4];
// 1 + 2 + 3 + 4
console.log(array1.reduce((accumulator, currentValue) => accumulator + currentValue));
// expected output: 10

every

every() 方法測試數組的全部元素是否都經過了指定函數的測試。it

function isBigEnough(element, index, array) {
  return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true

some

some() 方法測試是否至少有一個元素經過由提供的函數實現的測試。
對於放在空數組上的任何條件,此方法返回false。io

[2, 5, 8, 1, 4].some(x => x > 10);  // false
[12, 5, 8, 1, 4].some(x => x > 10); // true
相關文章
相關標籤/搜索