Front-end development school recruitment interview questions sorting [1] - JavaScript

Front-end development school recruitment interview questions sorting [1] - JavaScript

Written in front:

All the interview questions have been sorted out and shared on GitHub. Welcome to star.
Address: https://github.com/shadowings-zy/front-end-school-recruitment-question

1. Basics of JavaScript

Q: Introduce the basic data types of js?

Basic types (value types): String, Number, Boolean, Null, Undefined, Symbol, BigInt.

Number types include integers and floating-point numbers. The precision of integers is 2^53, and the highest precision of floating-point values ​​is 17 decimal places.
Also note that NAN belongs to the digital type and represents non-numbers, that is, 1/0=NAN, NAN/1=NAN.
Infinity represents a number that exceeds the range, with a plus or minus sign.

undefined: Indicates that the variable has been declared but does not contain a value.
null: Indicates that the variable is empty.

Reference types: objects, arrays, functions (in fact, they are all objects, and they are all references).

Data encapsulation objects: Object, Array, Boolean, Number, String
Other objects: Function, Arguments, Math, Date, RegExp, Error

Basic types are stored in stack memory and reference types are stored in heap memory

Q: How to judge the type of an object in js?

Use typeof to determine the type of a javascript basic object.

typeof 'John' // 返回 string
typeof 3.14 // 返回 number
typeof NaN // 返回 number
typeof false // 返回 boolean
typeof [1, 2, 3, 4] // 返回 object
typeof {
    
     name: 'John', age: 34 } // 返回 object
typeof new Date() // 返回 object
typeof function () {
    
    } // 返回 function
typeof myCar // 返回 undefined (如果 myCar 没有声明)
typeof null // 返回 object

Using constructor can return the type of a constructor, and the type can be judged according to the name of the constructor.

"John".constructor // 返回函数 String() {[native code]}
(3.14).constructor // 返回函数 Number() {[native code]}
false.constructor // 返回函数 Boolean() {[native code]}
[1,2,3,4].constructor // 返回函数 Array() {[native code]}
{
    
    name:'John', age:34}.constructor // 返回函数 Object() {[native code]}
new Date().constructor // 返回函数 Date() {[native code]}
function () {
    
    }.constructor // 返回函数 Function() {[native code]}

Use instanceof to detect reference types, such as:

console.log(person instanceof Object) // 变量 person 是 Object 吗?
console.log(colors instanceof Array) // 变量 colors 是 Array 吗?
console.log(pattern instanceof RegExp) // 变量 pattern 是 RegExp 吗?

Q: How do you understand the prototype chain of js?

prototype chain

As long as there is an object, there is a prototype, and the prototype is also an object, so as long as an object is defined, its prototype can be found, and so on, a sequence of objects can be formed, and this structure is called a prototype chain.

Each object will initialize a property inside it, which is the prototype (prototype). When we access the property of an object, if the property does not exist in the object, then he will go to the prototype to find the property, and the prototype will be I have my own prototype, so I keep looking for it like this, which is what we usually call the concept of prototype chain.

关系:instance.constructor.prototype = instance.proto

Q: What is the difference between function.call and function.apply in js?

function.apply(thisObj, [argArray])
function.call(thisObj, arg1, arg2,, argN);

apply: Call a method of an object to replace the current object with another object. For example: B.apply(A, arguments); That is, the A object applies the B function, that is, changes the B context from the initial context to the A context.

call: Call a method of an object, replacing the current object with another object. For example: B.call(A, args1, args2); that is, the A object calls the method of the B object.

Q: How do you understand scope in js?

Global scope: the object written in the outermost layer, or the variable written in the inner layer but not declared with var, the scope is global, for example:

var outerVar = "outer";
function fn() {
    
    
  innerVar = “inner”;
  console.log(outerVar);
}
fn(); //result:outer
console.log(innerVar); //result:inner

Function scope: write variables declared using var inside the function, for example:

function fn() {
    
    
  var innerVar = 'inner'
}
console.log(innerVar) // ReferenceError: innerVar is not defined

Scope chain: Internal functions can chain access to variables of external functions, for example:

name = 'aaa'

function b() {
    
    
  var name = 'bbb'

  function c() {
    
    
    var name = 'ccc'
    console.log(name) //ccc
  }

  function d() {
    
    
    console.log(name) //bbb
  }
  c()
  d()
}
b()
console.log(name) //aaa

Q: What is a closure in js?

Closures take advantage of the scope feature of js, and use functions whose return value is a function, so that the functions inside can access the variables of the outside functions. When we call the external function, we can call the return value function to modify the variables of the external function.

A closure is a function that can access variables in another function's scope.
Function:
1. It can reduce the objects of global variables, preventing global variables from being too large in the past, which makes it difficult to maintain.
2. Preventing constant modification.
3. Read the variables inside the function, so that the values ​​of these variables are always kept in memory.

For example:

const add = function () {
    
    
  let counter = 0
  return function () {
    
    
    counter++
    return counter
  }
}

const x = add()
console.log(x()) // 计数器为 1
console.log(x()) // 计数器为 2
console.log(x()) // 计数器为 3

2. JavaScript flow control

Q: Tell me about the usage of Promise in js?

The Promise object represents an asynchronous operation, which is not affected by the outside world, and has three states:
Pending // In progress, unfinished
Resolved // Completed, also known as Fulfilled
Rejected // Failed

The Promise object provides the following four methods:
then // call the method when the asynchronous operation is completed
catch // call the method when the asynchronous operation fails
all // call the method race after all function operations are completed
// call the method after the first one completes or fails

for example:

function read(time) {
    
    
  console.log('正在阅读')
  let p = new Promise(function (resolve, reject) {
    
    
    setTimeout(function () {
    
    
      console.log('阅读完毕')
      time = time + 1
      resolve(time)
    }, 2000)
  })
  return p
}

function write(time) {
    
    
  console.log('正在写作')
  let p = new Promise(function (resolve, reject) {
    
    
    setTimeout(function () {
    
    
      console.log('写作完毕')
      time = time + 1
      resolve(time)
    }, 2000)
  })
  return p
}

function rest(time) {
    
    
  console.log('正在休息')
  let p = new Promise(function (resolve, reject) {
    
    
    setTimeout(function () {
    
    
      console.log('休息完毕')
      time = time + 1
      resolve(time) //把promise的状态设置为resolved,成功
    }, 2000)
  })
  return p
}

function badDream(time) {
    
    
  console.log('正在做梦')
  let p = new Promise(function (resolve, reject) {
    
    
    setTimeout(function () {
    
    
      console.log('做了噩梦')
      time = time + 1
      reject(time) //把promise的状态设置为rejected,失败
    }, 2000)
  })
  return p
}

read(0)
  .then(function (data) {
    
    
    return write(data)
  })
  .then(function (data) {
    
    
    return badDream(data)
  })
  .then(function (data) {
    
    
    return rest(data)
  })
  .then(function (data) {
    
    
    console.log(data)
  })
  .catch(function (data) {
    
    
    //处理失败的方法
    console.log('第' + data + '步出错')
  })

const p1 = new Promise(function (resolve, reject) {
    
    
  setTimeout(function () {
    
    
    console.log('p1完成')
    resolve(11)
  }, 1000)
})

const p2 = new Promise(function (resolve, reject) {
    
    
  setTimeout(function () {
    
    
    console.log('p2完成')
    resolve(22)
  }, 2000)
})

const p3 = new Promise(function (resolve, reject) {
    
    
  setTimeout(function () {
    
    
    console.log('p3完成')
    resolve(33)
  }, 3000)
})

//all,所有函数都执行结束后,回调方法
Promise.all([p1, p2, p3]).then(function (data) {
    
    
  console.log('全部完成', data)
})

//race,第一个函数执行结束后,回调方法
Promise.race([write(1), rest(2)]).then(function (results) {
    
    
  console.log('准备工作完毕:')
  console.log(results)
})

Q: Tell me about the usage of async and await in js? The difference with Promise?

async is placed in front of the function as a keyword to indicate that the function is an asynchronous function.
Because async means asynchronous, an asynchronous function means that the execution of the function will not block the execution of the following code.
async will return a Promise object, such as our console.log(timeout()), will get a Promise object, if resolve will return hello world, if reject will throw an exception.
But this is not the point. The biggest advantage of async is that await can be used inside it, which can handle the then chain of Promise more concisely.
If there is no await in async, it is actually equivalent to a Promise object whose resolve returns a return value.

The await expression will suspend the execution of the current async function, waiting for the Promise to be processed. If the Promise is fulfilled normally, the resolve function parameter of the callback is used as the value of the await expression, and the async function continues to be executed. If the Promise handles an exception (rejected), the await expression will throw the Promise's exception reason. Also, if the value of the expression after the await operator is not a Promise, the value itself is returned.

The combination of async and await can handle Promise's then chain more intuitively.

For example:
How to write Promise:

doSomething()
  .then(function (res) {
    
    
    return doNext(res)
  })
  .then(function (nextRes) {
    
    
    return doFinalThing(nextRes)
  })
  .then(function (finalResult) {
    
    
    console.log('Got the final result: ' + finalResult)
  })
  .catch(failureCallback)

How to write async/await:

try {
    
    
  const result = await doSomething()
  const nextRes = await doNext(result)
  const finalResult = await doFinalThing(newResult)
  console.log('Got the final result: ' + finalResult)
} catch (error) {
    
    
  failureCallback(error)
}

3. JavaScript common data structures

Q: Tell me about some commonly used Array APIs?

The focus of Array's API is to be able to use it, not to know what the API is for

push(a)           // 末尾添加,返回数组长度
unshift(a)	      // 首位添加,返回数组长度
shift()	          // 删除第一个元素,并返回删除的元素
pop()	            // 删除最后一个元素,并返回删除的元素
join(a)	          // 把数组中的所有元素放到一个字符串中,分隔符为a
concat(a, b)	    // 将b连接到a后面
sort()	          // 数组排序
reverse()	        // 数组倒序
isArray(a)	      // a是否为数组
slice(a, b)	      // 根据输入的开始点和末尾点,截取出新的数组(包括前不包括后)
splice(a, b, c)	  // 从a位置开始,删除b长度的数组,插入c

indexOf(a)	      // 从前向后寻找值等于a的项,返回index
lastIndexOf(a)	  // 从后向前寻找等于a的项,返回index

every(function(item, index, array))	      // 对数组每一项运行一次某函数,若函数每一项都为true,返回true
some(function(item, index, array))	      // 对数组每一项运行一次某函数,若函数某一项为true,返回true
filter(function(item, index, array))	    // 对数组每一项运行一次某函数,返回返回值为true的项的数组
map(function(item, index, array))	        // 对数组每一项运行一次某函数,返回返回值的数组
forEach(function(item, index, array))	    // 对数组每一项运行一次某函数,无返回值
reduce(function(prev, cur, index, array)) //接收四个参数:前一个值、当前值、项的索引和数组对象,这个函数的任意返回值会作为第一个参数传给下一项。

Q: What is the difference between for in and for of traversing arrays/objects?

For arrays: for in outputs the array index value (subscript), and for of outputs the array elements.
For objects: for in outputs the object key value, and for of outputs the object value value.

Q: What is the code to implement flattening the array?

const arr = [1, 3, [3, 4, [5, 6]]]

// 第一种方案:用现成api,不兼容低版本的浏览器
const arr1 = arr.flat(Infinity)

// 第二种方案:原生循环递归实现
function flat2(arr) {
    
    
  const result = []
  arr.forEach((item) => {
    
    
    if (Array.isArray(item)) {
    
    
      result.push(...flat(item))
    } else {
    
    
      result.push(item)
    }
  })
  return result
}
const arr2 = flat2(arr)

// 第三种方案:使用解构和递归实现
function flat3(arr) {
    
    
  const result = [].concat(...arr.map((x) => (Array.isArray(x) ? flat(x) : x)))
  return result
}
const arr3 = flat3(arr)

Q: What is the code to realize the deep copy object?

// 对象中如果均为基本类型
JSON.parse(JSON.stringify(obj))

// 对象中如果既有基本类型,还有Array和Object
function deepCopy(data) {
    
    
  let output
  if (data === null || !(typeof data === 'object')) {
    
    
    output = data
  } else {
    
    
    output = data.constructor.name === 'Array' ? [] : {
    
    }
    for (let key in data) {
    
    
      output[key] = deepCopy(data[key])
    }
  }
  return output
}

Q: What is the difference between "test" and new String("test"), and what is the difference between {} and new Object()?

"test" is a constant of type string, and new String() creates a string object.

const obj1 = new String('abc') // 类型为object
const obj2 = 'abc' // 类型为string

obj1 == obj2 // true
obj1 === obj2 // false

Both {} and new Object() themselves create an object and return a reference to the object.

const obj1 = new Object('abc') // 类型为object
const obj2 = {
    
    } // 类型为obejct

obj1 == obj2 // false
obj1 === obj2 // false

4、DOM/BOM API

Q: How to use addEventListener? What is the difference with onxxx?

onxxx is the standard of DOM0, supported by all browsers, it will directly register the event name on the DOM object.
For example:

document.getElementById('click').onclick = function (event) {
    
    
  console.log(event.target)
}

addEventListener is a standard of DOM2, supported by browsers above IE8, it is divided into three stages: capture stage, target stage, and bubbling stage.
Each event is first passed from the root to the target element and then back to the root.

Q: What does event proxy refer to?

Event proxy means that in order to add events to multiple elements (such as li), we add events to the parent element of the element. When an event occurs, we capture the event target, judge the target, and execute the corresponding event e.target.

Q: How to use js to access cookies? If you want to prohibit access to cookies with js, what should you do?

Use document.cookie to view cookies. The cookie storage format is key=value;key=value;a string of the form.

Setting HttpOnly in the header can prevent js from accessing cookies.

Q: How to use js to calculate the viewable area of ​​the browser?

// 获取浏览器窗口的可视区域的宽度
const width = document.documentElement.clientWidth || document.body.clientWidth

// 获取浏览器窗口的可视区域的高度
const height = document.documentElement.clientHeight || document.body.clientHeight

Guess you like

Origin blog.csdn.net/u011748319/article/details/119898891