数组操作 map filter

在所有的数组操作中,最有用的还是map和filter。这两个方法能做的事绝对不能不提。

map
map可以将元素转换为数组。至于转换为什么数组,这就是map的优美之处:类型由开发者决定。
例如对象中包含数字,但是我们只需要数字,数组中包含函数,而需要Promise的情况,,,

map很容易满足这样要求,map和filter都不会修改原数组,而是返回数组的拷贝。

    var arr1 = [{
    
     name: 0 }, {
    
     name: 1 }, {
    
     name: 2 }, {
    
     name: 3 }, {
    
     name: 4 }]
    console.log(arr1.map(x => x.name))               //[0, 1, 2, 3, 4]
    console.log(arr1.map(c => c.name * 6))            //[0, 6, 12, 18, 24]

数组每个元素在调用提供的方法时都会传入三个参数:元素本身,元素的下标,以及数组本身(这个不常用)。

    const items = ['www', 'com']
    const arrls = ['111', '222']
    const cart = items.map((x, i) => ({
    
     name: x, index: arrls[i] }))
    console.log(cart)
    // [{name: "www", index: "111"},{name: "com", index: "222"}]

filter

filter 顾名思义,他是用来删除数组中不需要的元素,向map一样,它返回了删除后的数组,

  	var arr = [1, 2, 3, 4, 5]
    console.log(arr.filter(c => c > 3))    			// [ 4 , 5 ]
    console.log(arr.filter(c => c == 4))    		// [ 4 ]
    console.log(arr.filter(c => c < 6 && c > 4))    // [ 5 ]

那么如何将map和filter结合起来从而产生良好的效果。

    var arr = [1, 2, 3, 4, 5]
    console.log(arr.filter(c => c > 3).map(x => x*100))    // [ 400 , 500 ]
    //可能你会有疑问,为什么不直接在filter里面操作c,我们尝试一下
    console.log(arr.filter(c => (c > 3) * 100))    // [ 4 , 5 ]
    // *100 并没有生效

	//我们还可以在map中调用方法
	function C100 (c){
    
    
        return c * 100
    }
    var arr = [1, 2, 3, 4, 5]
    console.log(arr.filter(c => c > 3).map(C100) )  // [ 400 , 500 ]

猜你喜欢

转载自blog.csdn.net/qq_44977477/article/details/108616562
今日推荐