欢迎来到吴小小的专栏!

js里面的map、filter、forEach、reduce、for in、for of等遍历方法

1、map 遍历数组,改变原数组

[2, 3, 4, 5].map(function(val, key,arr) {
    return val > 3;
})

var data = [
    {
        name: 'tom',
        age: 22
    },
    {
        name: 'link',
        age: 19
    }
]
data.map(function(item, index) {
    return item.age += 20
})
console.log(data);

2、filter 不改变原数组,返回一个新数组

var person = [
    {
        name: 'tom',
        age: 20,
    },
    {
        name: 'jake',
        age: 25
    },
    {
        name: 'bis',
        age: 32
    },
    {
        name: 'alex',
        age: 28
    }
]
var aaa = person.filter(function(value,key,arr) {
    return item.age < 26
})
console.log(person, aaa);

3.reduce 叠加结果 回调函数中有4个参数,分别是,上一项叠加后的结果,当前项,当前项的索引值,数组本身

var thing = [
    {
        name: 'xiaom',
        price: 1999
    },
    {
        name: 'apple',
        price: 6666,
    },
    {
        name: 'huawei',
        price: 2999
    }
]
thing.reduce(function(res,cur,key,arr){
   return res + cur,price 
},0)

4.sort 从小到大排序

var produts = [
    {
        name: 'xssg',
        price: 10,
    },
    {
        name: 'xssg',
        price: 20,
    },
    {
        name: 'xssg',
        price: 8,
    },
    {
        name: 'xssg',
        price: 4,
    },
    {
        name: 'xssg',
        price: 7,
    },
    {
        name: 'xssg',
        price: 1,
    }
]
produts.sort(function(cur, nex) {
    return cur.price - nex.price;
})

5.forEach

缺点 :无法中途跳出forEach循环,break命令或return命令都不能奏效。

[1, 2, 3, 4].forEach(function(value, key, arr) {
	console.log(value, key, arr)
})

6.for in 遍历数组或者对象

缺点:数组的键名是数字,但是for...in循环是以字符串作为键名“0”、“1”、“2”;
不仅遍历数字键名,还会遍历手动添加的其他键,甚至包括原型链上的键。

var obj = {a:1, b:2, c:3};
    
for (var prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);
}

7.for of (只要部署了symbol.iterator接口)

优点:有着同for...in一样的简洁语法,但是没有for...in那些缺点。
不同于forEach方法,它可以与break、continue和return配合使用。
提供了遍历所有数据结构的统一操作接口。

posted @ 2017-10-25 16:12  吴小小  Views(895)  Comments(0Edit  收藏  举报