前言
数组是我们在编程的时候最常见的,但是有些时候我们会忘记一些数组的方法,偶尔我们才会用到,这里我们再来回顾一下。首先我们常见的数组方法一般如下几类:
1. 排序类:sort 、set、reserve
2. 统计类:reduce
3. 查找类(判断某一字符是否存在):some 、 includes、indexof 、lastindexof,filter
4. 增删类: pop shift push,unshift
排序类
定义数组进行升序和降序: arr=[1,2,5,3,4];
const arr = [1, 2, 5, 3, 4];
// 升序排序
const arr1 = arr.sort((a, b) => {
if (a > b) {
return 1
} else {
return -1
}
});
console.log(arr1); //打印结果 [1,2,3,4,5]
// 降序排序
const arr2 = arr.sort((a, b) => {
return b - a
});
console.log(arr2); //打印结果 【5,4,3,2,1】
// sort 排序的主要原理还是冒泡排序法
const test = [100,4,5,10,201];
// 进行倒序排序
const test1 =test.reverse();
console.log(test1); //打印结果【201,10,5,4,100】;
数组去重
const arr = [1, 2, 3,5, 3, 4];
const newarray = Array.from(new Set(arr));
console.log(newarray); // 打印结果 1 2,3,5,4
统计类
定义数组arr=【1,2,3,3,5,6】
const arr =[1,2,3,3,5,6];
// reduce方法的三个重要参数
// prev:上次调用函数的返回值
//
// cur:当前元素
//
// index:当前元素索引
// 统计当前数组所有项的和
const count = arr.reduce((pre,cur,index)=>{return pre+cur});
console.log(count); // 打印结果 20
// 根据条件统计某一项出现的次数
let num =0;
function test(Array) {
Array.reduce((pre,cur,index)=>{
return cur >3 ? num++ : num+0;
})
return num;
}
console.log(test(arr)); //打印结果2
查找类
//some 提供条件查看数组当中是否存在符合条件的值,存在返回true,反之返回false
// 条件: 数组当中是否存在大于10的数字
const test1 = [1,2,3,4,5].some((item)=>{return item>10});
const test2 =[3,6,10,11,90].some((item)=>{return item >10});
console.log(test1,test2); //打印结果:false true.
//includes 查询符合条件的值,存在返回true,反之返回false
// 条件:数组当中是否存在10
const test3 =[1,2,5].includes(10);
const test4 =[2,9,10,15].includes(10);
console.log(test3,test4); //打印结果:false true
//indexof lastindexof 查找符合条件的值是否存在,indexof返回第一个符合条件的下标值,lastindexof则是返回最后一个符合条件的下标值
const test5 = [1,4,3,5,4,3].indexOf(3);
const test6 = [1,4,3,5,4,3].lastIndexOf(3);
console.log(test5,test6); //打印结果 2,5;
增删类
const test =[1,2,3,4];
// 增加类:push 末尾添加
test.push(1);
console.log(test) //打印结果 1 、2,3,4,1
// 头部添加
test.unshift(1);
console.log(test)// 打印结果 1,1,2,3,4、1
// 删除类 pop 末尾删除
const test1 =[1,2,3,4];
test1.pop();
console.log(test1);// 打印结果 1、2、3
// shift头部删除
test1.shift();
console.log(test1) // 打印结果 2、3