ES6数组新增方法

ES6数组新增的一些常用的方法

  • forEach
  • map
  • filter
  • some
  • every
  • find
  • findIndex
  • findLast
  • findLastIndex
  • reduce

以上这些方法,用法都一样,效果不同

arr.方法名((item,index,arr)=>{
})

1. forEach

此方法是用来代替 for 循环遍历数组

let arr=[1,2,3,4];
arr.forEach(function(value,index,arr){
//在这里进行相关操作
})

2.map

返回值是一个新的 数组,数组长度和原数组相同,数组中的值,就是函数中的返回值。

let potatos = [
  { id: '1001', weight: 50 },
  { id: '1002', weight: 80 },
  { id: '1003', weight: 120 },
  { id: '1004', weight: 40 },
  { id: '1005', weight: 110 },
  { id: '1006', weight: 60 }
]
  let w = potatos.map(function(potato) {
        return potato.weight
    })
 //在这里,potato.weight就是函数的返回值

3.filter

此方法是依次拿出数组中的元素,返回符合要求的元素。返回值是一个新的数组,数组中的值是符合条件的值,而这个条件是函数的返回值。

let potatos = [
  { id: '1001', weight: 50 },
  { id: '1002', weight: 80 },
  { id: '1003', weight: 120 },
  { id: '1004', weight: 40 },
  { id: '1005', weight: 110 },
  { id: '1006', weight: 60 }
]
let bigPotatos=potatos.filter(potato=>potato.weight>=100)
//potato.weight>=100 就是返回值,为布尔值,如果为true,则当前遍历到potato就会作为新数组中的值

4.some

此方法返回值是布尔值,判断数组中是否有符合条件的值,而这个条件是函数的返回值

let potatos = [
  { id: '1001', weight: 50 },
  { id: '1002', weight: 80 },
  { id: '1003', weight: 120 },
  { id: '1004', weight: 40 },
  { id: '1005', weight: 110 },
  { id: '1006', weight: 60 }
]

let hasBig = potatos.some(potato => potato.weight >= 100)
// 只要返回值为true,则内部停止遍历,some返回值true,如果每次都返回false,则some返回值为false

5.every

返回值是布尔值,判断数组中的值是否都符合条件,如果是则返回true,有一个不符合则返回false

let potatos = [
  { id: '1001', weight: 50 },
  { id: '1002', weight: 80 },
  { id: '1003', weight: 120 },
  { id: '1004', weight: 40 },
  { id: '1005', weight: 110 },
  { id: '1006', weight: 60 }
]

let hasBig = potatos.every(potato => potato.weight >= 100)
// 只要所有返回值为true,则every返回true,如果由一次返回false,则every返回值为false

6.find 、findLast

返回值为符合条件的对应的那个值
后者从后往前遍历

let potatos = [
  { id: '1001', weight: 50 },
  { id: '1002', weight: 80 },
  { id: '1003', weight: 120 },
  { id: '1004', weight: 40 },
  { id: '1005', weight: 110 },
  { id: '1006', weight: 60 }
]

let bigPotato = potatos.find(potato => potato.weight >= 100) 
// 得到第一个符合条件的数据,返回给变量

7.findIndex 、findLastIndex

返回值为符合条件的对应的那个值的下标
后者从后往前遍历

let potatos = [
  { id: '1001', weight: 50 },
  { id: '1002', weight: 80 },
  { id: '1003', weight: 120 },
  { id: '1004', weight: 40 },
  { id: '1005', weight: 110 },
  { id: '1006', weight: 60 }
]

let bigPotato = potatos.findIndex(potato => potato.weight >= 100) 
// 得到第一个符合条件的数据的下标,返回给变量
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值