設計一個函式,輸入數字,輸出轉換成千分位顯示,如 1234567890=>1,234,567,890
function handlerNums(num) {
num = '' + num
const arr = num.split('').reverse()
let result = []
for (let i = 0, len = arr.length; i < len; i++) {
result.unshift(arr[i])
if (i > 0 && i < len - 1 && i % 3 == 2) {
result.unshift(',')
}
}
return result.join('')
}
實作防抖函式 debounce 和節流函式 throttle
let count = 0;
let dom = document.getElementById("app");
let input = document.getElementById("input");
function debounce(cb, wait = 1000) {
let timer = null;
return function() {
const args = [...arguments];
clearTimeout(timer);
timer = setTimeout(() =>{
cb.apply(this,args);
},wait);
}
}
function throttle(cb, wait) {
let timer = null;
let flag = false;
return function() {
if(flag) return;
const args = [...arguments];
if(!flag) {
flag= true;
timer = setTimeout(() =>{
cb.apply(this, args);
flag = false;
},wait);
}
}
}
input.addEventListener('keyup',throttle(function(){
console.log(this)
dom.innerHTML = this.value
},5000))
實現一個 LRU 快取模塊
class LRUModule {
constructor() {
this.idCatch ={};
this.timecatch = [];
}
add(data) {
if(this.idCatch[data.id]){
this.get(data.id);
return;
}
this.idCatch[data.id] = data;
if(this.timeCatch.length === 10){
const id = this.timecatch[e];
delete this.idCatch.id;
this.sort(e);
}
this.timeCatch.push(data.id);
this.idCatch[data.id].index = this.timeCatch.length - 1;
}
get(id){
let data = this.idcatch[id];
const i = data.index;
this.sort(i);
this.timeCatch.push(data.id);
data.index = this.timeCatch. length;
return data;
}
sort(index) {
this.timecatch.splice(index,1);
for( let i = index; i < this.timecatch. length; i++){
const id = this.timecatch[i];
this.idcatch[id].index--;
}
}
}
let obj = new LRUModule();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/254110.html
標籤:其他
