2022前端面试问题解答(2)

本文详细解析了JavaScript中作用域的实战应用、fn1-fn3函数的作用、Promise链的执行顺序、异步输出控制、闭包机制以及Promise和setTimeout的交互。通过实例演示了如何理解并利用这些概念解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.打印输出结果
考察点:作用域

let a = 0
function fn1() {
    let a1 = 100
    function fn2() {
        let a2 = 200
        function fn3() {
            let a3 = 300;
            return (a + a1 + a2 + a3)
        }
        fn3()
    }
    fn2()
}
fn1()
// 打印结果 undefind   因为 fn1内部没有return  fn2内部也没有return
// return 后打印 600

2.打印输出结果

		function test(a, b) {
            console.log(b)
            return {
                test: function(c) {
                    return test(c, a)
                }
            }
        }

        var retA = test(0) 
        retA.test(2) 
       //  第一次输出 undefind,只传了a,没有传b
       // 第二次考察的还是作用域的问题:所有的自由变量的查找,是在函数定义的地方向上级作用域查找,不是在执行的地方。所以输出0

3.点击a标签打印对应的数字

let a
for (let i =0; i< 10; i++){
    (
        function(_i){
            a = document.createElement('a');
            a.innerHTML = _i+"";
            a.addEventListener('click',function(e){
                e.preventDefault();
                alert(_i)
            })
            document.body.appendChild(a)
        }
    )(i)
}
// 1、for + let 会形成闭包,但是let i 必须要写在for里面才能形成闭包
// 2、因为触发事件是在for循环结束之后才能执行的,for循环最后跳出来的数是10,在没有closure保存每次for循环i的值的情况下就只能触发10。

3.Promise打印输出结果

Promise.resolve().then(()=>{
    console.log(1) 
}).catch(()=>{
   console.log(2) 
}).then(()=>{
   console.log(3) 
}) 

// 输出: 1   3
Promise.resolve().then(()=>{
    console.log(1) 
    throw new Error('error')
}).catch(()=>{
   console.log(2) 
}).then(()=>{
   console.log(3) 
})
//  输出  1   2    3
Promise.resolve().then(()=>{
    console.log(1) 
    throw new Error('error')
}).catch(()=>{
   console.log(2) 
}).catch(()=>{
   console.log(3) 
})
//  输出  1   2   

总结:then正常返回resolved,里面有报错返回rejeced
catch正常返回resolved, 里面有报错返回rejected

4.异步问题输出打印结果

console.log('start')
setTimeout(function() {
    Promise.resolve().then(function() {
        console.log('promise3')
    }).then(function() {
        console.log('promise4')
    })
    console.log('setTimeout1')
}, 0)
  
setTimeout(function() {
    console.log('setTimeout2');
}, 0)
  
Promise.resolve().then(function() {
    console.log('promise1')
}).then(function() {
    console.log('promise2')
})
console.log('end');
// start end promise1 promise2 setTimeout1 promise3 promise4 setTimeout2
//宏任务执行时,在执行下一个宏任务时,会将产生的微任务执行掉
//宏任务:setTimeout setInterval ajax DOM事件
//微任务:Promise  async/awiat
// 执行时机:普通函数 > 微任务 > 宏任务

5.输出打印结果

new Promise((resolve, reject) => {
  console.log(1);     // 同步部分,先执行(1)
  setTimeout(() => {  
    console.log(2);   // 异步部分,宏任务,先跳过。(1,7,3,4,2)
  });
  resolve();          // 改变promise状态为fulfilled
}).then(() => {       // Promise 的处理程序(handlers).then、.catch 和 .finally 都是异步的。可以都跳过了。跳到46行。
  console.log(3);     // 异步部分,微任务。(1,7,3)
}).then(() => {
  return new Promise((resolve, reject) => {
    console.log(4);   // 异步部分,微任务。(1,7,3,4)
  }).then(() => {     // promise状态为pending,不触发后续内容。
    console.log(5);
  });
}).then(() => {
  console.log(6);
});
console.log(7);       // 同步部分,执行。(1,7)

6.Promise 输出打印结果

function test(){
    return new Promise ((resolve,reject )=>{
        console.log(789)
    })
}
(async function a() {
    const result = await test()
    console.log(123)
})()
//  789
// 为什么没有输出  123? 因为promise 没有执行 resolve 
function test(){
    return new Promise ((resolve,reject )=>{
        console.log(789)
        resolve()
    })
}
(async function a() {
    const result = await test()
    console.log(123)
})()
// 789  123
  1. 异步输出打印结果
async function fn1( ) {
    return 100
}
const res1 = fn1()  // 执行 async 函数  返回的是一个 Promise 对象
res1.then(data => {
    console.log('data',data)  // 100
})

async function fn1( ) {
    return Promise.resolve(200)
}
const res1 = fn1()  // 执行 async 函数  返回的是一个 Promise 对象
res1.then(data => {
    console.log('data',data)  // 200
})


(async function () {
    const p1 = Promise.resolve(300)
    const data = await p1  // await 相当于Promise then
    console.log(data)  //300  
})() 

(async function () {
    const data = await 400 // 相当于 Promise.resolve(400)
    console.log(data)  //400
})()

8.异步async 输出打印结果

async function async1(){
    console.log(1)
    await async2()
    console.log(2)
}
async function async2() {
    console.log(3)
}
console.log(4)
async1()
console.log(5)
// 4   1   3   5  2

async function async1() {
    console.log(1);
    await async2();
    //await 后面  都可以看做是 callback 里的内容,即异步
    console.log(2);
}

async function async2() {
    console.log(3);
}

async1();

setTimeout(() => {
    console.log(4);
})

console.log(5);
// 1, 3, 5, 2, 4
console.log ('1')
setTimeout(function() {
  console.log('2')
}, 0)

new Promise(resolve => {
  console.log('3')
  resolve()
  console.log('4')

})
.then(function() {
  console.log('5')
})
.then(function() {
  console.log('6')
})
console.log('7')

// 正确答案: 1347562
new Promise((resolve)=> {
  setTimeout(()=> {
      console.log('setTime') //第三步(问题1)
      resolve('ok')
  }, 0)
  console.log('promise1') //第一步
}).then((res) => {
  console.log(res) //第四步(问题2)
  console.log('then')
})

console.log('local') //第二步

//promise1 -> local -> setTime -> ok -> then
// 问题1,需要先执行 resolve() ,再执行 then 里的函数。所以 'setTimeout' 会先于 then 内部函数打印

// 问题2,resolve('ok') 其实就是把 promise 实例变成 fulfilled 状态,顺便把 'ok' 作为参数传递给第一个 then 内部的函数,然后再微任务异步执行 then 内部的函数。

9.promise 和 setTimeout 的顺序

console.log(100)
setTimeout(()=>{
	console.log(200)
})
Promise.resolve().then(()=>{
	console.log(300)
})
console.log(400)
//   100 400 300 200  微任务>宏任务

10.头条网红面试题

async function async1 (){
    console.log('async1 start') // 2
    await async2()
    // await 后面的都作为回调内容  --微任务
    console.log('async2 end' ) // 6
}
async function async2() {
    console.log('async2') //  3
}
console.log('script start') // 第1步
setTimeout(()=>{ // 宏任务
    console.log('setTimeout')  //8
})
async1()
//初始化 promise 时 传入的函数会立刻被执行
new Promise (function (resolve){
    console.log('promise1') // 4
    resolve()
}).then(function(){ // 微任务
    console.log('promise2') // 7
})
console.log('script end') // 5

//script start  async1 start  async2  promise1  script end  async2 end  promise2  setTimeout
async function fn1(){
  console.log(3)
  await fn2()
  //异步
  console.log(4)
}

async function fn2(){
  console.log(5)
  await fn3()
  // 异步
  console.log(6)
}

async function fn3(){
  console.log(7)
}

console.log(1)
fn1()
console.log(2)
fn2()
//1 3 5 7 2 5 7 6 6 4
//你就看第一个函数 fn1 ,执行 fn1 时得先把内部的 await fn2()  执行完了,最后再执行 console.log(4) ,对吧?所以,无论怎么算,4 都是最后输出的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值