js pen test questions collection

 1. Microtasks and macrotasks

Macro-task and micro-task detailed explanation clickable execution mechanism

The JS execution mechanism is executed from top to bottom, synchronous code takes precedence over asynchronous code, and microtask takes precedence over macrotask execution

  async function async1() {
    console.log('async1 start')
    await async2()
    console.log('async1 end') // 相当于promise.then的异步回调
  }

  async function async2() {
    console.log('async2')
  }

  console.log('script start')

  setTimeout(function () {
    // 定时器作为宏任务的存在
    console.log('setTimeout')
  }, 0)

  async1()

  new Promise(function (resolve) {
    console.log('promise1')
    resolve()
  }).then(function () {
    console.log('promise2')
  })
  console.log('script end')

  // 'script start'
  // 'async1 start'
  // 'async2'
  // 'promise1'
  // 'script end'
  // 'async1 end'
  // 'promise2'
  // 'setTimeout'

2.this points to the problem

The this of the ordinary function points to

The arrow function this points to

The call method changes the point of this

  var num1 = 2
  var obj1 = {
    num1: 1,
    fun1() {
      console.log(this.num1 * 2)
    },
    fun2: () => {
      console.log(this.num1) // Math.PI ---圆周率3.141592653589793
    }
  }
  obj1.fun1() // 2   this指向调用的对象obj1
  obj1.fun2() // undefined
  // 箭头函数中的this指向不是指向调用的obj1  箭头函数的 this 是指向上一层全局环境的 this
  obj1.fun1.call({ num1: 3 }) // 6
  obj1.fun2.call({ num1: 3 }) // undefined
  // 箭头函数不存在this,所以call改变this不生效

3. Recursive application

  // 递归
  let obj = {
    'a.b.c': 1,
    'a.d': 2,
    e: 3
  }
  function flat(prop) {
    return Object.keys(prop).reduce((res, key) => {
      key.split('.').reduce((obj, k, index, arr) => {
        // debugger
        return (obj[k] = index == arr.length - 1 ? prop[key] : obj[k] || {})
      }, res)
      return res
    }, {})
  }
  console.log(flat(obj))

  // {
  //   a: { b: { c: 1 }, d: 2 },
  //   e: 3
  // }

4. Create dom elements natively

let arr = ['v1', 'v1', 'v2', 'v3']
  let newArr = []
  arr.forEach((item) => {
    let caleData = arr.filter((el) => el === item)
    if (caleData.length > 1) {
      newArr = [...caleData]
    }
  })
  console.log(newArr)
  // 原生创建dom元素页面循环渲染数据
  newArr.forEach((item, index) => {
    // debugger
    let div1 = document.createElement('div')
    // 设定属性名和属性值
    div1.setAttribute('id', `dom${index}`)
    div1.innerText = `${item}`
    document.body.appendChild(div1)
  })

5. Cyclic printing timing tasks

 for (var i = 0; i < 3; i++) {
    setTimeout(function () {
      console.log(i)
    }, 0)
  }

// 333

Guess you like

Origin blog.csdn.net/weixin_50543490/article/details/128241464