//算法基础:展平数组
//使用...
//只能展平两层
//
{
let arr = [1,[2,3],[4,5]];
let arr2 = '' ;
arr2=[].concat(...arr)
console.log(arr2)
}
//递归算法
{
let arr=[1,[2,3],[[[4,5]]]];
flatten(arr);
function flatten(arr){
return [].concat(
...arr.map(x => Array.isArray(x)?flatten(x):x)
)
}
console.log(flatten(arr))
}
//函数节流算法 距离上次执行超过60毫秒,才能执行
//思路:执行throttle后 ,lock就是一把锁,只有当lock为false时才执行func,
//这把锁需要throttle距离上次执行相隔60毫秒才能为false
{
function throttle(func,delay=60){
let lock = false;
return (...args) =>{
if(lock){return}
func(...args);
lock = true;
setTimeout( () =>{lock = false}, delay)
}
}
}
//函数节流二,算法 操作完后过多少时间 才执行
//思路:不停的操作,定时器就一直重复叠加执行,定时器i 也就一直在被重复,
//需要没次执行throttle时将上一次的定时器i清除,
{
function throttle(func,delay=300,i=null){
return (...args) => {
clearInterval(i);
i=setTimeout(func.bind(null,...args),delay);
//i=setTimeout((...args) =>func(...args),delay);// 同上
}
}
}
var data = [{
id: 1,
name:'家电',
goods: [{
id: 11,
gname:'冰箱',
goods: [{
id: 111,
gname:'海尔',
},{
id: 112,
gname:'美的',
}
]
},{
id: 12,gname:'洗衣机'
}]
},{
id: 2,
name:'服饰'
},{
id: 3,
name:'服饰'
},];
// 递归
//理解: 自己调用自己
//函数内部做了两件事 ==>
//1 满足条件时结束 ,
//2 不满足条件时,子项传入 , 继续
function getID(json,id){
var o=null;
json.forEach(function(item){
if (item.id == id) { //让最外层拿到o
o = item;
return item;
}else if (item.goods && item.goods.length) { //让里层拿到o
o = getID(item.goods,id);
}
})
return o;
}