實現一個遍歷domtree
function domtree(dom,index=0){
index++;//domtree深度
if (dom.nodeType === Node.ELEMENT_NODE) {
console.log(dom.tagName+":"+index)
}
let childNodes = dom.childNodes;
for (let i=0;i<childNodes.length;i++) {
if(childNodes[i].nodeType === Node.ELEMENT_NODE){
domtree(childNodes[i],index)
}
}
}複製程式碼
實現一個instanceof
function Instanceof(a,b) {
let proto = a.__proto__;
let prototype = b.prototype;
while (true){
if (proto === prototype) {
return true
}
if (proto == null) {
return false
}
proto = proto.__proto__;
}
}複製程式碼
防抖與節流
1.防抖
function debounce(func,wait){
let timer = null;
return function(...prm){
if(timer) clearTimeout(timer);
timer = setTimeout(()=>{
func(...prm)
},wait)
}
}複製程式碼
2.節流
function throttle(fn, wait) {
let prev = new Date();
return function() {
const args = arguments;
const now = new Date();
if (now - prev > wait) {
fn.apply(this, args);
prev = new Date();
}
}複製程式碼
深拷貝
function deepCopy(obj){
if(typeof obj == "object"){
var result = obj.constructor == Array ? [] : {};
for(let i in obj){
result[i] = deepCopy(obj[i]) ;
}
}else {
var result = obj;
}
return result;
}複製程式碼