数组几大功能分类
遍历
- Array.from(arr,fn) 第二个参数类似map
- Array.prototype.filter(fn) 过滤,返回过滤后新数组
遍历时,将返回值为true的元素放入新数组 - Array.prototype.forEach(fn) 同for循环
- Array.prototype.map(fn) fn必须得有返回值
案例:
[].map.call 区别于map():可以遍历类数组对象
public syncfixedTableRowHeight = () => {
let fixedfirstColRows =
this.fixedfirstColExceptFirstRow.querySelectorAll(".table-row");
let fixedColRowsHeights = [].map.call(fixedfirstColRows, (row: any) => {
const height = row.getBoundingClientRect().height;
return height;
});
this.setState({ fixedColRowsHeights });
};
将元素拿出来变换之后放到新数组中
- Array.prototype.reduce(fn,initVal) 返回值类型取决于initVal,第二个参数
fn(acc,curr){};
每次循环返回的值都会作为下次循环的acc参数
创建
- new Array(n) 创建元素为n个的数组
- Array.of(val1,val2…) 将参数转换为数组
- Array.from(arr) 将类数组转化为真数组,第一个参数
- Array.prototype.concat(arr) 如果有返回true;合并数组
- Array.prototype.flat([depth]) 数组扁平化
const arr = [1, [2, [3, [4, 5]]], 6];
const res1 = arr.flat(Infinity);
Infinity 是一个数值,表示无穷大。
- Array.prototype.keys(arr) 同Object.keys
- Array.prototype.values(arr) 同Object.values
检测
- Array.isArray(arr) 返回true/false
- Array.prototype.includes(val) 只能检测基本数据类型,-1
- Array.prototype.some(fn) 返回true/false
数组内部位移
- Array.prototype.copyWithin(target,[start,end])
- Array.prototype.fill(val, [start,[end]]) 固定值填充数组
数组往前补零
function zeros(num,n){
return new Array(n).fill(0).join('') + num;
}
- Array.prototype.reverse() 数组元素反转,会改变原数组
- Array.prototype.sort() 排序
查找下标
- Array.prototype.findIndex(fn) 可以完成复杂数据类型的查找
- Array.prototype.indexOf(val) 只能是基本数据类型
注意返回值
数组转字符串
- Array.prototype.join(separator) 缺省’ , ’ 只能进行基本数据类型的转化;
注意:
separator分隔符没有:返回的字符以‘,’逗号连接
'abcd'.split('').reverse().join() //'d,c,b,a'
separator分隔符为空‘’:则表示字符之间没有任何分隔符,连接在一起;
abcd'.split('').reverse().join('') //'dcba''
[1,2,3,{a:"a"}].join('') //"123[object object]"
增删改
- Array.prototype.pop() 删除数组最后一个元素,返回删除的元素,会改变原数组
- Array.prototype.shift() 删除数组第一个元素,返回删除的元素,会改变原数组
- Array.prototype.unshift(val1,val2) 添加到数组的第一个元素,返回数组的长度,会改变原数组
- Array.prototype.push(val) 添加元素到数组的最后,返回数组的长度,会改变原数组
- Array.prototype.slice([begin,[end]]) 原数组的浅拷贝,返回拷贝的数组;
- 如果begin/end为负数,[1,2,3,4,5].slice(-2,-1)表示:从倒数第2个,截取到倒数第1个;截取只能从左到右
- 想截取数组后面的元素:[1,2,3,4,5].slice(-3); 截取倒数第三个到最后的;==>[3,4,5] ;只传一个负数
- Array.prototype.splice(begin,[deleteCount,[val]]) 两个参数:删除 ; 三个参数:替换/添加 ; 返回删除的元素,没有删除的就是[]
- [1,2,3].splice(1,1) 从下标1开始,删除一个元素
- [1,2,3].splice(1,0,‘a’) 从下标1开始,添加’a’到下标1前面
- [1,2,3].splice(1,1,‘a’) 从下标1开始,替换下标为1的元素
问题:什么是数组迭代器对象?
是什么?是数组的泛化,任何对象都可以被定制为可以在for-of循环中使用的对象,数组可以迭代,但很多内置对象也可以迭代。对象是某物的集合,可以使用for-of遍历
能够适用for-of循环
有Symbol.iterator方法才可以迭代,返回一个迭代器即next()
有next()方法
参考
面试题
for和forEach的区别
- for循环可以使用break和trun终端当前循环,forEach不可以。
数组去重的方法
//方法1
let arr = [1,2,2,3];
let b = Array.from(new Set(arr));
//方法2
let a = arr.filter((item,index)=>arr.indexOf(item) === index);