扁平化n维数组
[1,2,[3,4]].flat(2);
[1,2,[3,4,[5,6]]].flat(2);
[1,2,[3,4,[5,6,[7,8,....]]].flat(Infinity);
function flatten(arr){
if(!Array.isArray(arr)) return arr;
while(arr.some(item => Array.isArray(item))){
arr = [].concat(...arr);
}
return arr;
}
console.log(flatten([1,2,[3,4]]));
console.log(flatten([1,2,[3,4,[5,6]]]));[1,2,3,4,5,6]
[1,2,[3,4].toString().split(",").map(item => Number(item));
[1,2,[3,4].toString().split(",").map(item => +item);
数组去重
Array.from(new Set([1,1,2,2,3,3]));
[...new Set([1,1,2,2,3,3])] ;
数组排序
[1,2,4,3,6].sort();
[1,2,4,3,5].sort((a,b) => b-a); [5,4,3,2,1]
Array.prototype.bubbleSort = function(){
let arr = this,
len = arr.length;
for(let outer = len; outer >=2; outer--){
for(let inner = 0; inner <=outer-1; inner++){
if(arr[inner] > arr[inner+1]){
[arr[inner], arr[inner+1]] = [arr[inner+1], arr[inner]];
}
}
}
return arr;
}
Array.prototype.selectSort = function(){
var arr = this,
len = arr.length;
for(let i =0; i<len; i++){
for(let j =i; j<len; j++){
if(arr[i] > arr[j]){
[arr[i], arr[j]] =[arr[j], arr[i]];
}
}
}
return arr;
}
console.log([1,2,5,2,1,3].bubbleSort());
console.log([1,2,5,2,1,3].selectSort());
最大值
Math.max(...[1,2,3,4]);
Math.max.apply(null,[1,2,3,4]);
[1,2,3,4].reduce((prev,cur,curIndex,arr) => {
return Math.max(prev,cur) ;
},0);
数组求和
[1,2,3,4].reduce((prev,cur) =>{
return prev + cur;
}
数组合并
[1,2,3,4].concat([5,6]);
[...[1,2,3,4],...[5,6]];
[1,2,3,4].push.apply([1,2,3,4],[5,6]);
判断是否包含某个值
[1,2,3].includes(4);
[1,2,3].indexOf(4);
[1,2,3].find(item => item ===3);
[1,2,3].findIndex( item => item ===3);
类数组转换
Array.prototype.slice.call(arguments);
Array.prototype.slice.apply(arguments)
Array.from(arguments);
[...arguments];
数组过滤
[1,2,3,4].every(item => {return item>2});
[1,2,3,4].some(item => {return item>2});
[1,2,3,4].filter(item =>{ return item>2});
对象数组转换
Object.keys({name:'zhangsan',age:14});
Object.values({name:'zhangsan',age:14});
Object.entries({name:'zhangsan',age:14});