1.数组的特点
1.1 概念:数组是一组数据的集合,在内存中是一段连续的内存空间。
1.2 定义数组
let arr1 = [];
let arr2 = new Array();
1.3 特点:无需指定数组长度,存储数据类型不限
2.数组常用API
1.push:数组后端插入,返回数组长度
2.pop:数组后端删除,返回删除项
3.unshift:数组前端插入,返回数组长度
4.shift:数组前端删除,返回删除项
5.slice(i,j):截取数组从i到j(不包括j)
6.join:转字符串(以传入参数分割)
7.splice(i,j,a):从第i位截取j个长度后替换成a
8.concat:拼接数组
9.reverse:翻转数组
10.indexOf:从头查找数组是否有该项,并返回下标,不存在返回-1
11.lastIndexOf:从尾查找数组是否有该项,并返回下标,不存在返回-1
12.includes:查找数组是否有该项,返回boolean
13.sotr:排序(快排)sort((a,b)=>a-b)升序 sort((a,b)=>b-a)降序
**push,pop,shift,unshift,splice,reveres,sort会改变原数组**
3.数组遍历API
1.for循环遍历
2.forEach
//两个参数:1.回调函数 2.执行 callback 时,用于 this 的值
//回调函数(值,下标,原数组)
//返回undefined
let arr = [1,2,3];
arr.forEach((value,index,arr)=>{},arr1);
3.map
//两个参数:1.回调函数 2.执行 callback 时,用于 this 的值
//回调函数(值,下标,原数组)
//返回回调函数中return的值组成的数组
let arr = [1,2,3];
arr.map((value,index,arr)=>{},thisArg);
4.filter
//两个参数:1.回调函数 2.执行 callback 时,用于 this 的值
//回调函数(值,下标,原数组)
//返回符合条件的项组成的数组
let arr = [1,2,3];
arr.filter((value,index,arr)=>{},thisArg);
5.reduce
//累加器:1.回调函数 2.作为第一次调用 callback函数时的第一个参数的值
//回调函数(累计器累计回调的返回值,当前值,下标,原数组)
//返回最后的res
let arr = [1,2,3];
arr.reduce((res,it,index,arr)=>{},[]);
6.some
//两个参数:1.回调函数 2.作为第一次调用 callback函数时的第一个参数的值
//回调函数(值,下标,当前数组)
//如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测
array.some(function(currentValue,index,arr),thisValue)
7.every
//两个参数:1.回调函数 2.作为第一次调用 callback函数时的第一个参数的值
//回调函数(值,下标,当前数组)
//如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
array.every(function(currentValue,index,arr),thisValue)
4.手写实现数组API
//1.手写forEach
Array.prototype.myforEach = function (fn,thisArr){
if(fn instanceof Function){
let arr = this;
thisArr = thisArr?thisArr:null;
for(let i=0;i<arr.length;i++){
fn.call(thisArr,arr[i],i,arr);
}
}
}
//2.手写map
Array.prototype.myMap = function (fn,thisArr){
if(fn instanceof Function){
let ans = [];
let arr = this;
thisArr = thisArr?thisArr:null;
for(let i=0;i<arr.length;i++){
ans[i] = fn.call(thisArr,arr[i],i,arr);
}
}
return ans;
}
//3.手写filter
Array.prototype.myFilter = function(fn,thisArr){
if(fn instanceof Function){
let ans = [];
let arr = this;
thisArr = thisArr?thisArr:null;
for(let i=0;i<arr.length;i++){
ans[i] = fn.call(thisArr,arr[i],i,arr);
}
}
return ans;
}
5.reduce用法
//1.数组去重
function unique1(arr){
return [...new Set(arr)]
}
function unique2(arr){
let newArr = [];
for(let i=0;i<arr.length;i++){
if(newArr.indexOf(arr[i]) == -1){
newArr.push(arr[i])
}
}
return newArr
}
function unique3(arr){
return arr.reduce((res,it)=>{
return res.includes(it)?res:[...res,it];
},[])
}
//2.数组扁平化
function flat1(arr){
return arr.reduce((res,it)=>{
return res.concat(Array.isArray(it)?flat(it):it)
},[])
}
function flat2(arr) {
while(arr.some(item=>Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}