简介:介绍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) //输出一个对像
}