es6数组方法详解

Array在ES5新增的方法中,参数都是function类型,默认有传参(对应项,对应的索引,数组本身)

因都为数组操作,我就在这里先声明所属变量,不必每次声明了

let fruits = ['apple', 'banana', 'orange'];
let people = [
  {
"name" : "kobe" ,
"age" : 36
  },
  {
"name" : "jordan" ,
"age" : 40
  },
  {
"name" : "james" ,
"age" : 34
  }
 ] 

1. forEach

 [].forEach(function(value, index, array) {
    // ...
 });

    forEach方法 遍历数组元素

 fruits.forEach(function(fruit,index) { 
    console.log(fruit,index);          // apple,0  // banana,1  // orange,2
 });

2. map   

    映射(一一对应)。

[].map(callback,[ thisObject]);

 callback必须有return值(如果没有,则返回undefined),下面介绍三个实例来了解一下吧

let arr1 = fruits.map(item=>(
    item.toUpperCase()
))
console.log(arr1); // ["APPLE", "BANANA", "ORANGE"]


let arr2 = people.map(item=>(
item.age
));
console.log(arr2); // [36, 40, 34]

var arr3 = people.map(item=>({
age : item.age
}));
console.log(arr3); //[{"age" : 36},{"age" : 40},{"age" : 34}]

3. filter

 过滤筛选(callback中通过返回true 或 false而filter从而返回所有符合过滤条件的元素)。

[].filter(callback,[ thisObject]);
let arr4= people.filter(item=>(
  item.age>36
)); console.log(arr4); // [{age:40,name:"jordan"}]

4. reduce 

   数组中的每个值(从左到右)开始缩减,最终计算为一个值。

   回调参数中的值 pre,cur.,curIndex,arr ( 上一次计算的值,当前项,当前索引,数组);

  initialValue 初始值可选项

[].reduce(callback[,initialValue]);
let total = people.reduce((pre,cur,currentIndex)=>(
  pre+cur
),0); console.log( tobal ); // 110

5. reduceRight 

  跟reduce方法完全一样,顺序为右开始计算

git 地址 : https://github.com/freshPork/grunt/blob/master/es6-array.html

posted @ 2017-12-21 10:17  MF孟飞  阅读(615)  评论(1编辑  收藏  举报