ES6和ES7之数组的扩展⽅法及扩展运算符的使⽤

简介:介绍ES6和ES7提供的新的数组⽅法及扩展运算符的使⽤

扩展运算符的使⽤ …
复制数组
分割数组
将数组转化成参数传递给函数

新增的常⽤⽅法
fill
find
findIndex
Includes
flat
filter

{
   // 扩展运算符的使⽤ ...

   //复制数组的使用
//    const list = [1,2,3,4,5]
//    const list2 = list
//    list.push(6)
//    console.log(list2)   输出[1,2,3,4,5] 这样达不到我们要复制数组的目的

    //使用宽展运算符复制数组
    const list = [1,2,3,4,5]
    let list2 = [...list]  //意思是把list数组一一展开,存放到list2数组
    list.push(6)
    console.log(list2)  //输出  [1,2,3,4,5]

    //分割数组
    const totalList = [1,'a','b','c']
    let [, ...strList] = totalList
    console.log(strList)  //输出  ['a','b','c']

    //给函数传递参数
    function fun(x,y){
        return x + y
    }
    let addList = [1,2]

    console.log(fun(...addList))  //输出 3

}

//新增的常⽤⽅法
{
    //fill 填充数据
    const list = [1,2,3,4,5]
    let list2 = [...list].fill(3)
    console.log(list2)  //输出 [3, 3, 3, 3, 3]

    let list3 = [...list].fill(3,1,4)  //注意第三个参数不是下标 而是第几项 
    console.log(list3)  //输出 [1, 3, 3, 3, 5]


}

{
    //find findIndex   寻找数据
    const list = [
        {title:'ES6'},
        {title:'webpack',id:2},
        {title:'Vue'},
        {title:'webpack',id:3}
    ]

    let result = list.find(function(item){
        return item.title === 'webpack'
    })
    console.log(result)  //输出 {title: "webpack", id: 2}   找到就不会继续往下找了 可以起到优化的作用

    let resultIndex = list.findIndex(function(item){
        return item.title === 'webpack'
    })
    console.log(resultIndex)   //输出 下标 1
}

{
    //includes  判断数据是否存在
    const list = [1, 2, 3, 4, 5]
    let result = list.includes(2)
    console.log(result)   //输出 true
}

{
    //flat 展开数组的操作
    // const list = [1, 2, [3,4,['cat',5,6]]]
    // let flatList = list.flat()
    // console.log(flatList)

    // chrome V68正式版报错"flat is not a function"

    // 升级浏览器至最新的V71方法可以正常使用
}

{
    //filter 对数据进行过滤
    const list = [
        {name:'cat',age:3},
        {name:'dog',age:2}
    ]
    //判断数据
    let result = list.filter(item => item.name === 'dog')
    console.log(result)  //输出一个对像
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值