数组操作 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 ]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值