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返回值為false5.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返回值為false6.find 、findLast
返回值為符合條件的對應的那個值
后者從后往前遍歷
7.findIndex 、findLastIndex
返回值為符合條件的對應的那個值的下標
后者從后往前遍歷
總結
- 上一篇: HTTP请求网页(包括HTTPS)
- 下一篇: 关于博客的一些感想