ES6 数组方法 forEach map filter find every some reduce
1. forEach
const colors = ['red', 'blue', 'green']
colors.forEach(function (params) { console.log(params) })
2. map 重构-返回数组
const porducts = [ { name: 'cucumber', type: 'vegetable', quantity: 0, price: 1 }, { name: 'cucumber', type: 'vegetable', quantity: 30, price: 10 }, { name: 'cucumber', type: 'fruit', quantity: 10, price: 16 }, ] porducts.map(function (params) { return params.price * 2 })
3. filter 过滤-返回数组
let porducts = [ { name: 'cucumber', type: 'vegetable', quantity: 0, price: 1 }, { name: 'cucumber', type: 'vegetable', quantity: 30, price: 10 }, { name: 'cucumber', type: 'fruit', quantity: 10, price: 16 }, ] porducts.filter(function (product) { return product.type === 'fruit' && product.quantity > 0 && product.price > 10 })
4. find 过滤-返回数组
let users = [ { name: 'jill', }, { name: 'alex', id: 0 }, { name: 'Bill', }, { name: 'alex', id: 1 } ] const use = users.find(function (params) { return params.name == 'alex' })
5. every 一假即假-返回Boolean
let computer = [ { name: 'apple', ram: 16 }, { name: 'IBM', ram: 4 }, { name: 'ACer', ram: 32 }, ] const com = computer.every(function (params) { return params.ram > 16 })
6. some 一真即真-返回Boolean
let computer = [ { name: 'apple', ram: 16 }, { name: 'IBM', ram: 4 }, { name: 'ACer', ram: 32 }, ] const comt = computer.some(function (params) { return params.ram > 16 })
7. reduce 返回值
1. 比较值获得最大值 let porducts = [ { name: 'cucumber', type: 'vegetable', quantity: 0, price: 21 }, { name: 'cucumber', type: 'vegetable', quantity: 30, price: 20 }, { name: 'cucumber', type: 'fruit', quantity: 10, price: 16 }, ] let prodList = porducts.reduce(function (first, last) { if (first < last.price) { first = last.price } return first }, 0)
2. 值与值想加 let number = [10, 50, 30] let sum = 0 let sumValue = number.reduce(function (sum2, number2) { // console.log(sum2) return sum2 + number2 }, 100)