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, 就停止循环
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章