javaScript面试题之看代码输出结果

241 阅读2分钟

常见的一些编程题(输出结果)

学习过程中的简单记录,若问题敬请指教!文章持续更新中...

路过的朋友,可以点个赞,关注一下~~~

1. 宏任务与微任务

 console.log(1)
 ​
 setTimeout(()=>{
     console.log(2)
 }, 0)
 ​
 new Promise((resolve, reject)=>{
     console.log('new Promise')
     resolve()
 }).then(()=>{
     console.log('then')
 })
 ​
 console.log(3)

结果: 1=>'new Promise'=> 3 => 'then' => 2

过程分析: 同步 > 异步(微任务 > 宏任务) ; 异步分为微任务与宏任务

常见的微任务与宏任务

宏任务:

  • script (可以理解为外层同步代码)
  • setTimeout / setInterval
  • UI rendering / UI事件
  • postMessage、MessageChannel
  • setImmediate、I/O(Node.js)

微任务:

  • Promise.then
  • MutaionObserver
  • Object.observe(已废弃;Proxy 对象替代)
  • process.nextTick(Node.js)

这里直接上代码:

 async function async1() {
     console.log('async1 start')
     await async2()
     console.log('async1 end')
 }
 async function async2() {
     console.log('async2')
 }
 console.log('script start')
 setTimeout(function () {
     console.log('settimeout')
 })
 async1()
 new Promise(function (resolve) {
     console.log('promise1')
     resolve()
 }).then(function () {
     console.log('promise2')
 })
 console.log('script end')

结果: script startasync1 startasync2promise1script endasync1 endpromise2settimeout

分析过程:

  1. 执行整段代码,遇到 console.log('script start') 直接打印结果,输出 script start
  2. 遇到定时器了,它是宏任务,先放着不执行
  3. 遇到 async1(),执行 async1 函数,先打印 async1 start,下面遇到await怎么办?先执行 async2,打印 async2,然后阻塞下面代码(即加入微任务列表),跳出去执行同步代码
  4. 跳到 new Promise 这里,直接执行,打印 promise1,下面遇到 .then(),它是微任务,放到微任务列表等待执行
  5. 最后一行直接打印 script end,现在同步代码执行完了,开始执行微任务,即 await下面的代码,打印 async1 end
  6. 继续执行下一个微任务,即执行 then 的回调,打印 promise2
  7. 上一个宏任务所有事都做完了,开始下一个宏任务,就是定时器,打印 settimeout

2. 结果输出值

 var length = 5
 function a() {
   console.log(this.length)
 }
 function b(fn) {
   fn()
   arguments[0]()
 }
 b(a, 1)
 ​
 // 结果 undefined  2 
 ​

后记

本文纯仅属于个人的一些简单的见解,比较浅显,若有不妥之处还请不吝赐教!!!(☆_☆)

如果本文对你有所帮助,欢迎点赞!!!

o( ̄▽ ̄)d