constlinearSearch=(arr, item)=>{for(const i in arr){if(arr[i]=== item)return+i;}return-1;};linearSearch([2,9,9],9);// 1linearSearch([2,9,9],7);// -1// 只返回数组中的第一个
绑定事件一次(前面也有类似函数)
constlistenOnce=(el, evt, fn)=>
el.addEventListener(evt, fn,{ once:true});// 可以传入 option(对象) 也可以传入 useCapture(布尔)listenOnce(
document.getElementById('my-id'),'click',()=> console.log('Hello world'));// 'Hello world' will only be logged on the first click
constrandomAlphaNumeric=length=>{let s ='';
Array.from({ length }).some(()=>{
s += Math.random().toString(36).slice(2);return s.length >= length;});return s.slice(0, length);};randomAlphaNumeric(5);// '0afad'
随机16进制颜色
constrandomHexColorCode=()=>{let n =(Math.random()*0xfffff*1000000).toString(16);return'#'+ n.slice(0,6);};randomHexColorCode();// '#e34155'
随机范围数组
constrandomIntArrayInRange=(min, max, n =1)=>
Array.from({ length: n },()=> Math.floor(Math.random()*(max - min +1))+ min
);randomIntArrayInRange(12,35,10);// [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
随机数
constrandomIntegerInRange=(min, max)=>
Math.floor(Math.random()*(max - min +1))+ min;randomIntegerInRange(0,5);// 2
创建一个生成器,该生成器使用给定的步长生成给定范围内的所有值
constrangeGenerator=function*(start, end, step =1){let i = start;while(i < end){yield i;
i += step;}};// for of 用于遍历集合 (迭代器对象)for(let i ofrangeGenerator(6,10)) console.log(i);// Logs 6, 7, 8, 9
requestAnimationFrame 动画帧的形式,调用回调,同时提供取消方法
constrecordAnimationFrames=(callback, autoStart =true)=>{let running =false,
raf;conststop=()=>{if(!running)return;
running =false;cancelAnimationFrame(raf);};conststart=()=>{if(running)return;
running =true;run();};construn=()=>{
raf =requestAnimationFrame(()=>{callback();if(running)run();});};if(autoStart)start();return{ start, stop };};constcb=()=> console.log('Animation frame fired');const recorder =recordAnimationFrames(cb);// logs 'Animation frame fired' on each animation frame
recorder.stop();// stops logging
recorder.start();// starts againconst recorder2 =recordAnimationFrames(cb,false);// `start` needs to be explicitly called to begin recording frames
constscrollToTop=()=>{const c = document.documentElement.scrollTop || document.body.scrollTop;if(c >0){
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c /8);}};// requestAnimationFrame api的运用,同时可以扩展(滚动到指定元素或者其他方向)// c - c / 8 距离的计算可以学习下(类似缓动动画?)