JS方法集合

1.JS分组

1
2
3
4
5
6
7
8
9
10
let getGroup=(data,key)=>{
let groups = {};
data.forEach(e=>{
let value = e[key];
groups[value] = groups[value] || [];
groups[value].push(e);
});
console.log(groups);
return groups;
}

2.基础防抖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function debounce(fn,delay){
let timer = null //借助闭包
return function() {
if(timer){
clearTimeout(timer)
}
timer = setTimeout(fn,delay)
}
}

function showTop () {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  console.log('滚动条位置:' + scrollTop);
}
window.onscroll = debounce(showTop,100)

3.清除所有定时器

1
2
3
4
let end = setInterval(function () { }, 10000);
for (let i = 1; i <= end; i++) {
clearInterval(i);
}

4. 打开新的独立窗口

1
2
let url = 'https://yuan67.top';
open(url, "_self ", "height=500,width=500,left=500,top=175,location=no,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,toolbar=no");

5. 生成递归树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let arr = [
{id:1, p:0,name:'湖北'},
{id:2, p:0,name:'四川'},
{id:3, p:1,name:'武汉'},
{id:4, p:3,name:'武昌'},
{id:5, p:3,name:'汉阳'},
{id:6, p:1,name:'荆州'},
{id:7, p:1,name:'十堰'},
{id:8, p:7,name:'郧西'},
{id:9, p:7,name:'武当'},
{id:10, p:2,name:'广安'},
{id:11, p:2,name:'成都'},
{id:12, p:2,name:'广元'}
]
let data = [];
arr.forEach(e=>{
e.child = arr.filter(el=>e.id == el.p)
if(e.p === 0) data.push(e);
})
console.log(data);

6.集合算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let a = [1,2,3,4]
let b = [1,2,3]
//交集
let intersect = a.filter(function(v){ return b.indexOf(v) > -1 })
//差集
let minus = a.filter(function(v){ return b.indexOf(v) == -1 })
//补集
let complement = a.filter(function(v){ return !(b.indexOf(v) > -1) })
.concat(b.filter(function(v){ return !(a.indexOf(v) > -1)}))
//并集
let unionSet = a.concat(b.filter(function(v){ return !(a.indexOf(v) > -1)}));
console.log("数组a:", a);//[1,2,3,4]
console.log("数组b:", b);//[1,2,3]
console.log("a与b的交集:", intersect);//[1, 2, 3]
console.log("a与b的差集:", minus);//[4]
console.log("a与b的补集:", complement);//[4]
console.log("a与b的并集:", unionSet);//[1, 2, 3, 4]

评论