ES6数组新增方法
ES6數(shù)組新增的一些常用的方法
- forEach
- map
- filter
- some
- every
- find
- findIndex
- findLast
- findLastIndex
- reduce
以上這些方法,用法都一樣,效果不同
arr.方法名((item,index,arr)=>{ })1. forEach
此方法是用來代替 for 循環(huán)遍歷數(shù)組
let arr=[1,2,3,4]; arr.forEach(function(value,index,arr){ //在這里進(jìn)行相關(guān)操作 })2.map
返回值是一個新的 數(shù)組,數(shù)組長度和原數(shù)組相同,數(shù)組中的值,就是函數(shù)中的返回值。
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就是函數(shù)的返回值3.filter
此方法是依次拿出數(shù)組中的元素,返回符合要求的元素。返回值是一個新的數(shù)組,數(shù)組中的值是符合條件的值,而這個條件是函數(shù)的返回值。
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,則當(dāng)前遍歷到potato就會作為新數(shù)組中的值4.some
此方法返回值是布爾值,判斷數(shù)組中是否有符合條件的值,而這個條件是函數(shù)的返回值
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,則內(nèi)部停止遍歷,some返回值true,如果每次都返回false,則some返回值為false5.every
返回值是布爾值,判斷數(shù)組中的值是否都符合條件,如果是則返回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返回值為false6.find 、findLast
返回值為符合條件的對應(yīng)的那個值
后者從后往前遍歷
7.findIndex 、findLastIndex
返回值為符合條件的對應(yīng)的那個值的下標(biāo)
后者從后往前遍歷
總結(jié)
- 上一篇: HTTP请求网页(包括HTTPS)
- 下一篇: 关于博客的一些感想