acongm
面试题库面试题记录

2025-04-28-面试题

1、以下代码输出什么

var a = {}
b = { key: 'b' }
c = { key: 'c' }
a[b] = 123
a[c] = 456
console.log(a[b]) // 456

2、请写出下面的结果,为什么

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

解析:

  • var 声明的 i 是全局作用域,循环结束后 i=5
  • setTimeout 回调共享最终的 i,所有输出均为 5

3、请写出下面的输出结果,最好说明一下原因

function Fn() {
  var num = 10
  this.x = 100
  this.getx = function () {
    // 修正语法错误
    console.log(this.x)
  }
}
var f1 = new Fn()
console.log(f1.num) // undefined(局部变量无法通过实例访问)
console.log(num) // 报错:num未定义
console.log(f1.getx) // 输出函数体(方法未被调用)

关键点 ​:

  • 局部变量 num 无法被实例或外部访问
  • this.x 是实例属性,需通过 f1.x 访问

4、请写出以下结果

fn() // 2
function fn() {
  console.log(1)
}
fn() // 2
var fn = 10
fn() // 报错:fn不是函数
function fn() {
  console.log(2)
}
fn() // 报错:fn不是函数

5、var a='a123',b='b234',请在不调用其他变量的情况下,互换 a,b 的值

let a = 'a123',
  b = 'b234'
;[a, b] = [b, a] // ES6解构赋值直接交换

6、分别写出下面两段代码的输出结果

for (var i = 0; i < 5; i++) {
  ;(function () {
    setTimeout(function () {
      console.log(i)
    }, 1000 * 1)
  })(i)
}
// 5 5 5 5 5
for (var i = 0; i < 5; i++) {
  ;(function (i) {
    setTimeout(function () {
      console.log(i)
    }, 1000 * 1)
  })(i)
}
// 0 1 2 3 4

7、根据下列代码,写出结果,并说明原因

setTimeout(() => {
  console.log(1)
}, 0)
new Promise((resolve, reject) => {
  console.log(2)
  setTimeout(() => {
    console.log(3)
    reject(4)
  }, 0)
}).then((val) => {
  console.log(val)
})
setTimeout(() => {
  console.log(5)
}, 0)
console.log(6)

输出顺序 ​:

  • 同步代码:2 → 6
  • 宏任务:1 → 3 → 5
  • 微任务:4
  • ​ 结果 ​:2 → 6 → 1 → 3 → 4 → 5

8、有 3 个基于 Promise 的异步函数,A,B,C; 写出按顺序 A-B-C 调用的代码(前一个函数完成后才能执行后一个函数)

// 链式调用实现
A()
  .then(() => B())
  .then(() => C())

// async/await实现
async function execute() {
  await A()
  await B()
  await C()
}

On this page