js原生面试总结

发布时间:2024-01-17 15:01:38

冒泡循环

var arr=[2,1,3,4,9,7,6,8]    
// 外层循环代表循环次数  内层循环时每次的两两对比 少一次循环
for (let i = 0; i < arr.length-1; i++) {
    // 如果进入判断代表当前值大于下一个是需要进行冒泡排序的
    let bool=true
    for (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] = element
            bool=false
        }
    }
    // 如果第一轮判断就实现排序就跳出
    if(bool){
        break;
    }
}

console.log(arr)

防抖函数

// 防抖定义变量一定要在全局中如果在函数中每次点击都重新生成一个


function debounce(callback,time){
    let timer=null;
    let isNodeFirst=false
    return function(){
        if(timer){
            clearTimeout(timer)
        }
        if(!isNodeFirst){
            callback.apply();
            isNodeFirst=true
        }else{
            timer=setTimeout(()=>{
                callback.apply();
                // 如果当前不重新赋值每次点击时就不会立即执行第一次
                isNodeFirst=false
                timer=null;
            },time)
        }
    }
}
let dd=debounce()
// 点击事件执行的是当前函数
// dd()

节流函数(节流参考)

function aa(){
    console.log(e.target.value)
  }
  function throttle(callback,delay){
    // 初始值必须定义在全局
    let start=0
    return function(){
      let current=Date.now()
    //如果初始时间为0   第一次不执行
      if(start==0){
        start = current
      }
      if((current-start)>delay){
        start=current
        callback.apply()
      }
    }
  }
 const th = throttle(aa,1000)

// 每次执行事件都是这个函数
//  th()

// 定时器执行   执行第一次立即执行
 function throttle(callback,delay){
    let timer=null;
    let start=0
    return function(){
       if(timer){
        clearTimeout(timer)
       }
       let current =+new Date()
       if(current-start>delay){
        callback.apply()
        start=current
        return;
       }
       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), '--');
    
文章来源:https://blog.csdn.net/weixin_43796856/article/details/135648153
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。