常用數組API

ES5/ES6/ES7/ES8

  • 數組常用方法

    • Array.indexOf():得到值在數組中的第一個下標,沒找到返回-1
      使用示例:找到數組中是否包含某個元素,返回Boolean值
    return ['春','夏','秋','冬'].indexOf('夏') !== '-1' 
    
    • Array.join(): 把數組轉成需要的字符串
    const arr = [1, 2, 3, 4, 5, 6, 7]
    const str1 = arr.join() // 1,2,3,4,5,6,7
    const str2 = arr.join('-') // 1-2-3-4-5-6-7
    
  • Array.slice(start,end)

    const sliceArr = arr.slice(3) // [4, 5, 6, 7]
    
  • Array.some()

    const isBoolean = arr.some((item, index) => item > 5) // true
    
  • Array.filter()

    const filterArr = arr.filter(item => {return item > 5}) // [6, 7]
    
  • Array.forEach()

    arr.forEach(function(item, index, a) {
            console.log(item, index, a)
            console.log(this) // [1, 2, 3, 4, 5, 6, 7]
        }, arr)
        
    arr.forEach( item => {
        item*3
        console.log(this) // window
    }, arr)
    
  • Array.map()

     const mapArr = arr.map(item => item*3) // [3, 6, 9, 12, 15, 18, 21]
    
  • Array.reduce()

    const reduceArr = arr.reduce((prev, item, index) => prev + item) // 28
    

    如果我們需要實現這樣一個對象 { a: 1, b: 2, c: 3 ...}

     const newArr = 'a,b,c,d,e,f'.split(',').reduce((acc, cur, idx) => {
        let o = {}
        if (Object.prototype.toString.call(acc) !== '[object Object]') {
            o[cur] = idx
        } else {
            let newO = {}
            newO[cur] = idx
            o = {
                ...acc,
                ...newO,
            }
        }
        return o
    }, 'a')
    console.log(newArr) // {a: 0, b: 1, c: 2, d: 3, e: 4, f: 5}
    
  • Array.flat(depth)

    arr.push([3, 4, 5, 9]) // [1, 2, 3, 4, 5, 6, 7, [3, 4, 5, 9]]
     // depth: 1,2, ... , Infinity
    const flatArr = arr.flat(1) // [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 9]
    
  • Array.splice(index, howmany)

    const spliceArr = arr.splice(1,1) // [2, 3, 4, 5, 6] 改變原數組
    console.log(spliceArr)
    console.log(arr) // [1, 7]
    
  • Array.find()

        const findArr = [1, 2, 3, 4].find(item => item > 2 ) // 3
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章