functiondeepTraversal1(node,nodeList =[]){if(node !==null){
nodeList.push(node)let children = node.children
for(let i =0; i < children.length; i++){deepTraversal1(children[i],nodeList)}}return nodeList;}
深度优先遍历 非递归
functiondeepTraversal2(node){let stack =[];let nodes =[];if(node){
stack.push(node)while(stack.length){let item = stack.pop()let children = item.children;
nodes.push(item)for(let i = children.length -1; i >=0; i--){
stack.push(children[i])}}}return nodes;}
广度优先遍历
functionbfs(node){let nodes =[];let stack =[];if(node){
stack.push(node)while(stack.length){let item = stack.shift()let children = item.children
nodes.push(item)for(let i =0;i < children.length; i++){
stack.push(children[i])}}}return nodes;}
浅拷贝
functionclone(target){let cloneTarget ={};for(const key in target){
cloneTarget[key]= target[key];}return cloneTarget;}
// 订阅器模型let Dep ={
clientList:{},// 添加订阅listen:function(key, fn){(this.clientList[key]||(this.clientList[key]=[])).push(fn);},// 发布trigger:function(){// 将类数组转化为数组let key =Array.prototype.shift.call(arguments),
fnd =this.clientList[key];if(!fns || fns.length ===0){returnfalse;}for(let i =0,fn; fn = fns[i++];){fn.apply(this,arguments)}}}//数据劫持/**
* data:我们要劫持的数据
* datakey:具体的属性值
* selector:dom节点
*/letmydatadefineProperty=function({data, tag, datakey, selector}){let value ='',
el = document.querySelector(selector);
Object.defineProperty(data,datakey,{get:function(){return value;},set:function(val){
value = val;// 发布
Dep.trigger(tag, val);}})// 订阅
Dep.listen(tag,function(text){
el.innerHtml = text;})}
改造为输出0-9
for(var i =0; i<10; i++){setTimeout(()=>{
console.log(i);},1000)}
// 1 setTimeout 第三个参数for(var i =0; i <10; i++){setTimeout(i=>{
console.log(i);},1000, i)}// 利用letfor(let i =0; i <10; i++){setTimeout(()=>{
console.log(i);},1000)}//立即执行函数iife,构造出块级作用域for(var i =0; i <10; i++){(i=>{setTimeout(()=>{
console.log(i);},1000)})(i)}// 利用try catchfor(var i =0; i <10; i++){try{throw i;}catch(i){setTimeout(()=>{ console.log(i);},1000)}}
var a = ?;如何输出1
if(a ==1&& a ==2&& a ==3){
console.log(1);}
// 1、重写toStringvar a ={
i:1,toString(){return a.i++;}}if( a ==1&& a ==2&& a ==3){
console.log(1);}// 2、利用valueOflet a ={
i:1,valueOf(){return a.i++}}if(a ==1&& a ==2&& a ==3){
console.log('1');}