常用数组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
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值