冒泡循环
var arr=[2,1,3,4,9,7,6,8]
// 外层循环代表循环次数 内层循环时每次的两两对比 少一次循环
for (let i = 0; i < arr.length-1; i++) {// 如果进入判断代表当前值大于下一个是需要进行冒泡排序的let bool=truefor (let j = 0; j < arr.length-1-i; j++) {// 虽然进不去判断但是依然会将第二轮循环走完if(arr[j]>arr[j+1]){// 中间值的作用暂存当前值const element = arr[j];arr[j] = arr[j+1]arr[j+1] = elementbool=false}}// 如果第一轮判断就实现排序就跳出if(bool){break;}
}console.log(arr)
防抖函数
// 防抖定义变量一定要在全局中如果在函数中每次点击都重新生成一个
call 传字符串 apply 传数组 bing 返回方法传数组function debounce(callback,time){let timer=null;let isNodeFirst=falsereturn function(){if(timer){clearTimeout(timer)}if(!isNodeFirst){callback.apply();isNodeFirst=true}else{timer=setTimeout(()=>{callback.apply();// 如果当前不重新赋值每次点击时就不会立即执行第一次isNodeFirst=falsetimer=null;},time)}}
}
let dd=debounce(aa,1000)
// 点击事件执行的是当前函数
// dd()
function aa(){console.log(e.target.value)}function throttle(callback,delay){// 初始值必须定义在全局let start=0return function(){let current=Date.now()//如果初始时间为0 第一次不执行if(start==0){start = current}if((current-start)>delay){start=currentcallback.apply()}}}const th = throttle(aa,1000)// 每次执行事件都是这个函数
// th()// 定时器执行 执行第一次立即执行function throttle(callback,delay){let timer=null;let start=0return function(){if(timer){clearTimeout(timer)}let current =+new Date()if(current-start>delay){callback.apply()start=currentreturn;}timer=setTimeout(()=>{callback.apply()timer=null;},delay)}}
//获取固定的深层嵌套对象var user = {name: 'xxx',address: {city: 'hangzhou'}};const str = 'address.city';const get = (obj, path, defaultValue) => {let result = obj, i = 0;const paths = path.split('.');while (i < paths.length) {result = Object(result)[paths[i]];if (result === undefined) {return defaultValue;}i++}return result;};console.log(get(user, str), '--');