JS笔记

350 阅读1分钟
  • 遍历重置对象属性

traversalObject(obj) {
      for (var a in obj) {
        const type = Object.prototype.toString.call(obj[a])
        if (type === '[object Object]') {
          this.traversalObject(obj[a]) // 递归遍历
        }
        if (type === '[object Array]') {
          obj[a] = []
        }
        if (type === '[object String]') {
          obj[a] = ''
        }
        if (type === '[object Number]') {
          obj[a] = 0
        }
        if (type === '[object Boolean]') {
          obj[a] = false
        }
      }
    }
  • 带参数的函数作为参数传递的执行顺序

    • 直接传入fun(arg),会先执行作为参数的函数,再进入调用的函数,若想后执行作为参数的函数:

    1、使用匿名函数(推荐使用,不改变原有函数结构)
    function doConsole(str) {
        console.log(`in doConsole`)
        console.log(str)
    }
    
    function triggerConsole(func){
        console.log(`in trigger`)
        if(func!=""&&func!=null){
            if(confirm("确认输出?")){
                func();
            }
        }
    }
    
    triggerConsole(doConsole("a")) // 依次输出in doConsole、a、in trigger,在判断语句中func为undefined 
    triggerConsole(function(){doConsole("a")}) //匿名函数,依次输出in trigger、a、in doConsole
    
    2、改写功能函数(和方法一类似,其他调用函数的执行变得麻烦doConsole("a")())
    function doConsole(str) {
        return function (){
            console.log(`in doConsole`)
            console.log(str)
        }
    }
    
    function triggerConsole(func,str){
        console.log(`in trigger`)
        if(func!=""&&func!=null){
            if(confirm("确认输出?")){
                func(str);
            }
        }
    }
    
    triggerConsole(doConsole("a")) // 输出in trigger、a、in doConsole
    
    3、可以将为参函数的参数独立传入,如下所示
    function doConsole(str) {
        console.log(`in doConsole`)
        console.log(str)
    }
    
    function triggerConsole(func,str){
        console.log(`in trigger`)
        if(func!=""&&func!=null){
            if(confirm("确认输出?")){
                func(str);
            }
        }
    }
    
    triggerConsole(doConsole("a")) // 依次输出in doConsole、a、in trigger
    triggerConsole(doConsole,'a') // 依次输出in trigger、a、in doConsole