一、改变原数组
- push:向数组尾部添加元素,返回添加后数组的长度。
- pop:去除数组最后一个元素,返回被去除的元素。
- shift: 去除数组第一个元素,返回被去除的元素。
- unshift:向数组头部添加元素,返回添加后数组的长度。
- reverse:数组倒序,返回顺序完全相反的数组。
- sort:数组排序(默认是从小到大),返回排序后的数组。
- splice:方法向/从数组中添加/删除项目,返回被删除的项目。
方法大家都知道,但是返回可能就容易被人忽略。
代码:
var arr = [2,4,5,6]
// push
// console.log(arr.push(1)) 5
// pop
// console.log(arr.pop()) 6
// shift
// console.log(arr.shift()) 2
// unshift
// console.log(arr.pop('1')) 5
// reverse
// console.log(arr.reverse()) [6, 5, 4, 2]
// sort
// sort默认情况下是返回从小到大,如果你想返回从大到小。可以向下面这样写
// console.log(arr.sort()) [2,4,5,6]
// console.log(arr.sort((a,b)=> b-a)) [6, 5, 4, 2]
// splice
// console.log(arr.splice(2,1,3)) 返回[5],原数组变为 [2, 4, 3, 6]
二、数组遍历方法
先假设一组数据:
var 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 }
]
1、forEach()方法和map()方法—遍历
两种方法都是对数组的遍历,但是不同的是map方法有返回值。如果不需要返回的话,语义上使用forEach方法更合适。
// forEach: 对数组每一个项进行操作,返回undefined
potatos.forEach(potato => potato.weight += 20 )
// map: 对数组每一个项进行操作,并返回操作后的结果
w = potatos.map(potato => { return potato.weight += 20 })
//[ 70, 100, 140, 60, 130, 80 ]
注意:forEach不能break也不能return!
2、filter()方法—遍历筛选
filter方法主要做的就是筛选过滤的事,看单词就能知道他的作用。
var bigOnes = potatos.filter(potato => { return potato.weight > 100 })
// [ { id: '1003', weight: 120 }, { id: '1005', weight: 110 } ]
// 返回满足条件的数组,并不改变原数组
3、some()方法—某一个符合
当只需要判断数组中有没有符合条件的时候(一个就行) 就需要我们的some方法登场了。返回的是true或false,相当于有或者无。
var hasbig = potatos.some(potato => { return potato.weight > 100 })
//true
只要找到一个符合条件的,就会返回true 。所以并不会全部遍历。
4、every()方法—全符合
判断数组中的项,是否全部符合某种条件。当有某一个不符合时,直接返回false。
var allbig = potatos.every(potato => { return potato.weight > 100 })
//false
5、find()方法—返回第一个符合的项
find和some很类似,都是寻找符合条件的,有一个就可以 不过some进去搜罗了一圈回来报了个“有”(true),而find则把那个抱出来(返回第一个符合条件的对象),找不到的话返回undefined
var big = potatos.find(potato => { return potato.weight > 100 })
//{ id: '1003', weight: 120 }
6、findIndex()方法—返回第一个符合的项的index值
findIndex方法的原理和find的一样只是返回的东西不一样,findIndex返回的是index,找不到的话返回-1
var i = potatos.findIndex(potato=>{ return potato.weight > 100 })
//2
findIndex返回第一个符合条件的索引号
7、reduce()—递归累加
var sum = potatos.reduce((sum, p) =>
{ return p.weight + sum },0)
//460
//并不会改变原数组
reduce()方法接收一个回调函数作为第一个参数,回调函数又接受四个参数,分别是;
- previousValue =>初始值或上一次回调函数叠加的值;
- currentValue => 本次回调(循环)将要执行的值;
- index=>“currentValue”的索引值;
- arr => 数组本身;
reduce()方法返回的是最后一次调用回调函数的返回值;
reduce()还有一些很棒的高阶应用,具体大家可以去查阅相关资料看看。