JS

Set

Set本身是一个构造函数,用来生成 Set 数据结构

Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 可用来排除重复的内容

const s = new Set();
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));

for (let i of s) {
console.log(i);
}
// 2 3 5 4

// 去除数组的重复成员
[...new Set(array)]
// 可以用于,去除字符串里面的重复字符
[...new Set('ababbc')].join('')
// "abc"

上面代码通过add()方法向 Set 结构加入成员,结果表明 Set 结构不会添加重复的值。

Set函数可以接受一个数组(或者具有 iterable 接口的其他数据结构)作为参数,用来初始化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 例一
const set = new Set([1, 2, 3, 4, 4]);
[...set]
// [1, 2, 3, 4]

// 例二
const items = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
items.size // 5

// 例三
const set = new Set(document.querySelectorAll('div'));
set.size // 56

// 类似于
const set = new Set();
document
.querySelectorAll('div')
.forEach(div => set.add(div));
set.size // 56

函数防抖

这个 debounce 函数在给定的时间间隔内只允许你提供的回调函数执行一次,以此降低它的执行频率。
当遇到高频触发的事件时,这样的限制显得尤为重要。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};

// 用法
var myEfficientFn = debounce(function() {
// 频繁执行的函数
console.log(1);
}, 250);
window.addEventListener('resize', myEfficientFn);

};

禁止重复调用、只允许执行一次的once 函数

很多时候,我们只希望某种动作只能执行一次,就像是我们使用 onload 来限定只在加载完成时执行一次。
下面这个函数就能让你的操作执行一次后就不会再重复执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    function once(fn, context) { 
var result;

return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}

// 用法
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});

canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada

console

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 声明
console.log(['%c轩', '%c时间: 2020-12', '%c主页: wuruixuan.com', '%cgithub: www.github.com/wuruixuan2464', '%c座右铭: I am just a ordinary people 😊'].join('\n').toString(),
`
background:url(http://www.wellyyss.cn/images/logo.png) no-repeat left center;
background-size:30px 40px;
padding-left:40px;
line-height:50px;
font-size: 18px;
font-weight:bold;
color:#00D4FF
`,
`
background:none;
line-height:30px;
font-size: 18px;
font-weight:bold;
color:#00D4FF
`,
`
padding-left:40px;
background:none;
line-height:30px;
font-size: 18px;
font-weight:bold;
color:#00D4FF
`,
`
background:none;
line-height:30px;
font-size: 18px;
font-weight:bold;
color:#00D4FF
`,
`
padding-left:40px;
background:none;
line-height:30px;
font-size: 18px;
font-weight:bold;
color:#00D4FF
`
)