1,LRU算法
LRU算法:即最近最久没有使用的缓存方法。
设计思想是主要实现get和set方法。
capacity:是缓存的容量大小
Map:用于存放缓存的数据结构
var LRUcache = function (capacity) {
this.capacity = capacity;
this.cache = new Map();
};
LRUcache.prototype.get = function (key) {
if (this.cache.has(key)) {
value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
return value;
} else {
return -1;
}
};
LRUcache.prototype.put = function (key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else {
if (this.cache.size >= this.capacity) {
this.cache.delete(this.cache.keys().next().value);
}
}
this.cache.set(key, value);
};
2,请把<ul><li>第1行</li><li>第2行</li>...</ul>(ul之间有10个li元素)插入body里面,注意:需要考虑到性能问题
可以把li链接为字符串,然后再统一修改,因为操作dom的开销是很大的。
let ulEle = document.createElement('ul')
let liList = ''
for (let i = 0; i < 10; i++) {
liList += `<li> 第${i}行 </li>`;
}
ulEle.innerHTML = liList;
document.body.appendChild(ulEle)
3,不使用loop循环,创建一个长度为100的数组,并且每个元素的值等于它的下标。
错误的实现:
new Array(100).map((item,index)=>index);
因为new Array(100)创建的是长度为100的空数组,所以使用map循环不到每一项,可以用以下方式实现:
new Array(100).join(',').split(',').map((item,index)=>index);
4,实现对数组乱序,使用数组的sort实现:
let arr = [2, 4, 5, 1, 3, 4]
arr.sort(function (a, b) {
let index = Math.random() > 0.5 ? 1 : -1
return (a - b) * index
})
5,有一个长度为100的数组,请以优雅的方式求出该数组的前10个元素之和。
let arr = [2, 4, 5, 1, 3, 4]
sum = arr.slice(0, 10).reduce(pre, current){
return pre + current
}