ES6數組方法總結

1. forEach()

forEach() 方法對數組的每個元素執行一次提供的函數。(注意,也就是forEach會遍歷數組, 沒有返回值, 不允許在循環體內寫return, 不會改變原來數組的內容.)

語法
Array.forEach( callback[, thisArg] )
例子
var array1 = ['a', 'b', 'c'];
array1.forEach(function(element) {
  console.log(element);
});
參數

callback 爲數組中每個元素執行的函數,該函數接收三個參數:
currentValue 數組中正在處理的當前元素。
index可選 數組中正在處理的當前元素的索引。
array可選 forEach() 方法正在操作的數組。
thisArg可選 可選參數。當執行回調函數時用作 this 的值(參考對象)。

2. map()

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

語法
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])
例子
let array = [1, 2, 3, 4];
let temp = array.map((item, index, array) => {
  return item * 10;
});
console.log(temp);  //  [10, 20, 30, 40];
console.log(array);  // [1, 2, 3, 4]
let temp2 = array.map(String);  // 把數組裏的元素都轉成字符串
參數

callback 生成新數組元素的函數,使用三個參數:
currentValue callback 數組中正在處理的當前元素。
index可選 callback 數組中正在處理的當前元素的索引。
array可選 map 方法調用的數組。
thisArg可選 執行 callback 函數時值被用作this。

3. filter()

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

語法
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
例子
let array = [1, 2, 3, 4];
let temp = array.filter((item, index, array) => {
  return item >  3;
});
console.log(temp);  // [4]
console.log(array);  // [1, 2, 3, 4]
// filter 會過濾掉數組中不滿足條件的元素, 把滿足條件的元素放到一個新數組中, 不改變原數組

參數

callback 用來測試數組的每個元素的函數。返回 true 表示該元素通過測試,保留該元素,false 則不保留。它接受以下三個參數:
element 數組中當前正在處理的元素。
index可選 正在處理的元素在數組中的索引。
array可選 調用了 filter 的數組本身。
thisArg可選 執行 callback 時,用於 this 的值。

返回值

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

4. reduce()

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

語法
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
例子
let array = [1, 2, 3, 4];
let temp = array.reduce((x, y) => {
  console.log("x": x);
  console.log("y": y);
  return x + y;
});
console.log(temp);  // 10
console.log(array);  // [1, 2, 3, 4]
// x 是上一次計算過的值, 第一次循環的時候是數組中的第1個元素
// y 是數組中的每個元素, 第一次循環的時候是數組的第2個元素
參數

reducer 函數接收4個參數:
Accumulator (acc) (累計器)
Current Value (cur) (當前值)
Current Index (idx) (當前索引)
Source Array (src) (源數組)

every 和some比較好理解就舉個例子就行了

5. every()

例子
let array = [1, 2, 3, 4];
let bo = array.every((item, index, array) => {
  return item > 2;
});
console.log(bo);    // false;
// every遍歷數組, 每一項都是true, 則返回true, 只要有一個是false, 就返回false

6. some()

例子
let array = [1, 2, 3, 4];
let tmep = array.some((item, index, array) => {
  return item > 1;
});
console.log(temp);  // true
// 遍歷數組的每一項, 有一個返回true, 就停止循環
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章