数组拓展
1.类方法
Array.from() 将类数组转数组
Array.of() 创建数组
// Array.from() const divs = document.getElementsByTagName('div') Array.from(divs).forEach(v => { console.log(v) }) // Array.of() const arry = Array.of(1,2,3)
2.实例方法
copyWithin(pos,start,end) // pos黏贴位置, start复制的起始位置, end 复制的结束位置
find() findIndex()
entries() keys() values()
flat() flatMap()
// 实现copyWithin() Array.prototype.myCopyWithin = function(pos,start,end){ return this.splice(pos,end-start+1,...this.slice(start-1,end)),this } const arry = [0,1,2,3,4,5,6,7,8,9] console.log(arry.copyWithin(3,4,8)) console.log(arry.myCopyWithin(3,4,8))
3.其它数组方法
splice(pos,count,a1,a2,a3)
4.flat拓展
/* * 实现flattenDeep */ // 方法1 - 递归 function flattenDeep(arr){ let newArr = [] arr.forEach(v => { if(Object.prototype.toString.call(v) === '[object Array]') newArr = [...newArr,...flattenDeep(v)] else newArr = [...newArr,v] }) return newArr }
// 方法2 - falt方法
function flattenDeep(arr){
return arr.flat(Math.pow(2,53)-1)
}
// 方法3 - reduce
function flattenDeep(arr){
return arr.reduce((arr,v) => Array.isArray(arr)?arr.concat(flattenDeep(v)):arr.concat(v),[])
}
// 方法4 - pop
function flattenDeep(arr){
const stack = [...arr]
const ret = []
while(stack.length){
const next = stack.pop()
if(Array.isArray(next)){
stack.push(...next)
}else{
ret.push(next)
}
}
return ret.reverse()
}
const ret = flattenDeep([1, [2, [3, [4]], 5,[6,[7,[8,[9,10,11,12]]]]]]);
console.log(ret)
5.数组去重
/* * 数组去重 */ // 方法1 - reduce function uniq1(arr){ return arr.reduce((pre,v) => pre.includes(v)?pre:[...pre,v],[]) } // 方法2 - set function uniq2(arr){ return [...new Set(arr)] } // 方法3 - map function uniq(arr){ let map = new Map() let result = [] arr.forEach(v => { if(map.has(v)){ map.set(v,true) }else{ map.set(v,false) result.push(v) } }) return result }
6.克隆数组
[].concat()