js做用域问题
js事件处理器在线程空闲时间不会运行,致使最后运行的时候输出的都是同一个值
1.使用闭包缓存当前值的生存周期es6
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();