五、scriptOJ和一些用到的函数
2019-02-12 本文已影响0人
懒羊羊3号
1、随机数组
[...(new Array(31)).keys()] // 产生顺序数组
.sort(() => Math.random() - Math.random())
2、
Object.prototype.toString.call(new Date) // [object Date]
(new Date).constructor.name //Date
3、找出两个数组的不同项
treeArr.forEach(x=>{
if (expandedKeys.indexOf(x) === -1) {
console.log(x)
}
})
套路
4、函数防抖
如果你疯狂、高频地调用某个函数,而调用之间的时间间隔低于某个时间段,这个函数最后只会被执行一次;如果高于某个时间段,则会执行多次。
const debounce = (fn, duration) => {
let timer = null;
return () => {
clearTimeout(timer)
timer = setTimeout(() => {
fn()
}, duration)
}
}
5、截流
function throttle (fn, delay) {
let timer = null,
remaining = 0,
previous = new Date();
return function () {
let now = new Date(),
remaining = now - previous,
args = arguments,
context = this;
if (remaining >= delay) {
if (timer) {
clearTimeout(timer);
}
// 大于时间间隔执行函数
fn.apply(context, args);
previous = now;
} else { // 小于时间间隔,如果没有timer就创建,有timer就忽略此次操作
if (!timer) {
timer = setTimeout(function () {
fn.apply(context, args);
previous = new Date();
}, delay - remaining);
}
}
};
}
6、set
set.size
set.has(1)
set.add(3) //返回新set
set.delete(1) //返回true or false
7、ascii\unicode
let a='a'
a.charCodeAt() //97
var num = 97;
String.fromCharCode(num); // 'a'
str.charCodeAt(1)