数组方法:
- forEach
- map
- filter
- some
- every
- indexof
- lastIndexof
- reduce
- reduceRight
- splice
- join
- sort
- reverse
- push
- pop
- unshift
- shift
- concat
1. forEach
forEach是Array中最基本的一个,就是遍历,循环。
forEach(value, index, array) value当前值, index当前索引, array当前数组
[1,2,3,4,5,6].forEach((value,index, array) =>{
console.log(value, index,array)
})
1 0 [ 1, 2, 3, 4, 5, 6 ]
2 1 [ 1, 2, 3, 4, 5, 6 ]
3 2 [ 1, 2, 3, 4, 5, 6 ]
4 3 [ 1, 2, 3, 4, 5, 6 ]
5 4 [ 1, 2, 3, 4, 5, 6 ]
6 5 [ 1, 2, 3, 4, 5, 6 ]
3. map
这里的map是映射的意思, 用法跟forEach类似,map() 方法返回一个新数组,而且map() 不会改变原始数组,也是原数组被映射成对应的新数组
[1,2,3,4,5,6].map((value,index, array) =>{
console.log(value, index,array)
})
1 0 [ 1, 2, 3, 4, 5, 6 ]
2 1 [ 1, 2, 3, 4, 5, 6 ]
3 2 [ 1, 2, 3, 4, 5, 6 ]
4 3 [ 1, 2, 3, 4, 5, 6 ]
5 4 [ 1, 2, 3, 4, 5, 6 ]
6 5 [ 1, 2, 3, 4, 5, 6 ]
if(typeof Array.prototype.map !== undefined) {
Array.prototype.map = function(fn, context) {
var mapArr = []
if(typeof fn == 'function'){
for(var k = 0, length = this.length, k < length; k++) {
mapArr.push(fn.call(context, this[k], k, this))
}
}
return arr
}
}
3. filter
filter是过滤,指定filter后,返回过滤后的数组,用法跟map很相似,返回新数组,filter()不会改变原始数组。array.filter(callback,[thisObject])
function farr(afa) {
return afa > 5
}
console.log([1,2,3,4,5,6].filter(farr)) // [6]
4. some
指某些项符合条件,some有一项符合返回true
function farr(afa) {
return afa > 5
}
console.log([1,2,3,4,5,6].some(farr)) // true
5. every
指某些项符合条件,every每一项都符合返回true
function farr(afa) {
return afa > 5
}
console.log([1,2,3,4,5,6].every(farr)) // false
6. indexOf
方法返回数组的第一个符合条件的索引
console.log([1,5,2,3,4,5,6].indexOf(5)) // 1
7. lastIndexof
用于返回数组的第一个符合条件的索引,是从尾部开始
8. reduce
reduce.function(previous, current, index, array) {
previos上一次值
current 当前值
index 索引
array 当前数组
}
求最大值
var reduceMaxNumber = [10,1,2,3,4,5,6].reduce(function (prev, cur) {
return Math.max(prev,cur);
});
console.log(reduceMaxNumber) // 10
数组去重
var newArr = arr.reduce(function (prev, cur) {
prev.indexOf(cur) === -1 && prev.push(cur);
return prev;
},[]);
reduce的好文章,强烈建议阅读 https://www.jianshu.com/p/541b84c9df90
9. reduceRight
reduceRight()方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。
10. splice
splice直接对原数组进行修改,删除,添加.返回被删除的元素
console.log([1,2,3,4,5,6,7].splice(0, 2)); // 1 2
var aaa = [1,2,3,4,5,6,6]
aaa.splice(2,0,'123') // []
console.log(aaa) // [1, 2, '123', 3, 4, 5, 6, 6]
11. join
join方法也可将所有数组元素结合为一个字符串
console.log([1,2,3,4,5,6].join('')); // 123456
12. sort
sort排序改变原数组
let sortRise = [5,2,4,51,63,12,54,6,32,21].sort((a,b) => {
return a - b
}) // 升序
let sortDown = [5,2,4,51,63,12,54,6,32,21].sort((a,b) => {
return a - b
}) // 降序
13. reverse
改变原数组,倒序
14. push
用于在数组尾部添加一个或多个元素
15. pop
用于删除并返回数组的最后一个元素 改变原数组
16. unshift
用于数组的开头添加一个或更多元素,并返回新的长度
17. shift
shift方法用于把数组的第一个元素从其中删除,并返回第一个元素的值
18. concat
用于连接两个或多个数组
let concat1 = [1,2,3,3]
let concat2 = [5,6,9,7,5]
console.log(concat1.concat(concat2)); // [1, 2, 3, 3, 5,6, 9, 7, 5]