作用域两个数简单求和移动端事件简单应用

17次阅读

共计 1636 个字符,预计需要花费 5 分钟才能阅读完成。

js 作用域问题
js 事件处理器在线程空闲时间不会运行,导致最后运行的时候输出的都是同一个值

1. 使用闭包缓存当前值的生存周期

for (var i = 1; i <= 5; i++) {(function (k) {setTimeout(function () {console.log(k)
        }, 1000)
    })(i)
}

2.es6 属性 声明 let 会有自己的作用域

for (let i = 0; i < 5; i++) {setTimeout(function () {console.log(i)
    }, 1000)
}

写一个函数,对于一个排好序的数组,如果当中有两个数的和为某个给定的数 target,返回 true,否则 false,时间复杂度 O(n)

function combination(arr, target) {for (var i = 0; i < arr.length - 1; i++) {for (var j = i + 1; j < arr.length; j++) {if (arr[i] + arr[j] === target)
                return true;
        }
    }
    return false
}
/** 
 * 题目
 *  @1.setTimeout(function() {console.log(1);
    }, 100);
    @2.setTimeout(function () {console.log(2);
    }, 0)
    @3.Promise.resolve(console.log(3)).then(() => { console.log(4) })
    @4.async function async1(){console.log(5)
    await async2()
    console.log(6)
    }
   @5. async function async2(){console.log(7)
    }
  @6. async1()
  @7.console.log(8)
* @answer 3 5 7 8 4 6  2 1
 遵循原则:同步 ==》异步 ==》回调函数 
 编号 @1@2 是一个回调函数所以放在最后执行
 编号 @3 作为一个 Promise 对象 首先 Promise 的出现是因为 js 是单线程的一门语言,单线程只能按照顺序去执行 A 执行完了 B 才开始执行,所以执行代码会造成阻塞,Promise 是为了解决这个所给我们带来困扰问题的一种异步解决方案,因此 @3>@2>@1
 编号 @4 async 实际上只是 Generator 函数的语法糖 async 函数就是将 Generator 函数的星号(*)替换成 async 仅此而已
 async 函数返回一个 Promise 对象 await(等待) await 命令后面的 Promise 对象执行完,才会发生状态改变
 所以 @4 可以直接打印出 5 但是必须等待 async2 的完成才可以打印 6
 所以此时的顺序是 @3(then 是结果此时是异步操作)@6>>@7@5>@2>@1
 因此结果是:3 5 7 8 4 6  2 1

touchstart : 触摸开始(手指放在触摸屏上)
touchmove : 拖动(手指在触摸屏上移动)
touchend : 触摸结束(手指从触摸屏上移开)

class touchEvent {constructor(target, away) {
        this.dom = target;
        this.away = away;
    }
    getDom() {document.querySelector(this.dom).addEventListener(this.away, this.touchStart)
    }
    touchStart = (e) => {
        /** 
         * 记录起始点
        */
        // 触摸开始
        document.querySelector(this.dom).addEventListener('touchmove', this.touchMove)
    }
    touchMove = (e) => {
        // 触摸中
        document.querySelector(this.dom).addEventListener('touchend', this.touchEnd)
    }
    touchEnd = (e) => {// 触摸结束}
}
new touchEvent('#swiper', 'touchstart').getDom();

正文完
 0