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)
// 得到第一个符合条件的数据的下标,返回给变量