The most common interview questions and answers JavaScript Year 2019

2019 year has passed, and in 2020 the peak of the interview again. After 2019 study and interview experience, some of the following statistics of the most common interview questions.

JavaScript in casts (coercion) What does it mean?

Difficulty: Easy

In JavaScript, the conversion between two different built-in types are called casts. There are two forms of forced transformation in JavaScript: explicit and implicit.

This is an example of an explicit casts:

var a = "42";
var b = Number( a );
a;                // "42" -- 字符串
b;                // 42 -- 是个数字!

This is an example of an implicit casts:

var a = "42";
var b = a * 1;    // "42" 隐式转型成 42 
a;                // "42"
b;                // 42 -- 是个数字!

JavaScript in scope (scope) What does it mean?

Difficulty: Easy

In JavaScript, every function has its own scope. Scope is basically a collection of variables and how to access these variables rule by name. Only in the function code to access the variable function scope.

The same scope of variable names must be unique. A scope can be nested in another scope. If a scope is nested in another scope, the code innermost scope can access another variable scope.

Equality interpret JavaScript.

Difficulty: Easy

JavaScript has a strict comparison and casts comparison:

  • Strict comparison (e.g. ===) to check whether the two values ​​are equal in a case where the transition can not be forced;
  • Abstract comparison (e.g. ==) to check whether the two values ​​are equal in the case of allowing forced transition.
var a = "42";
var b = 42;
a == b;            // true
a === b;        // false

Some simple rules:

  • If any of the values ​​being compared may be true or false, use === instead of ==;
  • If any value is compared these specific values ​​(0, "", or []), use === instead ==;
  • In other cases, you can safely use ==. It is not only safe, but also, in many cases, it can simplify the code, and to enhance code readability.

Explain what is a callback function, and provides a simple example.

Difficulty: Easy

The callback function is passed as a parameter to another function, and to perform certain operations after completion. Here is a simple example of a callback function, the printing function is complete message after certain operations to the console.

function modifyArray(arr, callback) {
  // 对 arr 做一些操作
  arr.push(100);
  // 执行传进来的 callback 函数
  callback();
}

var arr = [1, 2, 3, 4, 5];

modifyArray(arr, function() {
  console.log("array has been modified", arr);
});

What does "use strict" is?

Difficulty: Easy

use strict appears at the top, or function of JavaScript code that can help you write more secure JavaScript code. If you mistakenly create a global variable, it will pass to warn you throw the wrong way. For example, the following procedure will throw an error:

function doSomething(val) {
  "use strict"; 
  x = val + 10;
}

It will throw an error because x is not defined, and uses a value of the global scope of its assignment, and use strict does not allow it. The following small fixes for this error:

function doSomething(val) {
  "use strict"; 
  var x = val + 10;
}

null and undefined interpret JavaScript.

Difficulty: Easy

There are two types of underlying JavaScript: null and undefined. They represent different meanings:

  • It has not been initialized things:undefined
  • Currently unavailable things:null
  • typeof are not the same

Function may perform a write operation.

Difficulty: simple

var addSix = createBase(6);
addSix(10); // 返回 16
addSix(21); // 返回 27

A closure can be created to store the value passed to the function of createBase. Returned internal function was created in an external function, the function becomes an internal closure, which functions can access external variables, in the present embodiment is variable in baseNumber.

function createBase(baseNumber) {
  return function(N) {
    // 我们在这里访问 baseNumber,即使它是在这个函数之外声明的。
    // JavaScript 中的闭包允许我们这么做。
    return baseNumber + N;
  }
}

var addSix = createBase(6);
addSix(10);
addSix(21);

JavaScript explain the value and type

Difficulty: Easy

JavaScript typed value, but no type variables. JavaScript provides the following built-in types:

  • string
  • number
  • boolean
  • null 和 undefined
  • object
  • symbol (ES6 are added)
  • bigint

Event bubbling and explain how to stop it?

Difficulty: Easy

Event bubbling refers to the most deeply nested element trigger an event, then this event down the nested sequence trigger on the parent element.

A method for preventing the event bubbling or using event.cancelBubble that event.stopPropagation () (below IE 9).

let keyword in JavaScript what's the use?

Difficulty: Easy

In addition to the function level than the declared variable, ES6 also allows you to use the let keyword in the code block ({..}) declared variable.

How to check whether a number is an integer?

Difficulty: Easy

Check the number is decimal or integer, you can use a very simple way, it is to be modulo 1, to see if more than a few.

function isInt(num) {
  return num % 1 === 0;
}

console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false

What is IIFE (immediately call the function expression)?

Difficulty: Easy

It is calling the function expression (Immediately-Invoked Function Expression) immediately referred IIFE. Function is executed immediately after being created:

(function IIFE(){
    console.log( "Hello!" );
})();
// "Hello!"

How to compare two objects in JavaScript?

Difficulty: Moderate

For two non-original value, such as two objects (including arrays and functions), and === == comparison check whether they are just a reference match, and does not check the content actually referenced.

For example, by default, the array will be forced to transition into a string, with commas and all the elements of the array are connected together. Therefore, the two arrays having the same content will not be equal when compared ==:

var a = [1,2,3];
var b = [1,2,3];
var c = "1,2,3";

a == c;        // true
b == c;        // true
a == b;        // false

Beggars deep copy version

var obj1 = {
  a: 1,
  b: 2,
  c: 3
}
var objString = JSON.stringify(obj1);
var obj2 = JSON.parse(objString);
obj2.a = 5;
console.log(obj1.a);  // 1
console.log(obj2.a); // 5

For comparative depth of the object, you can use deep-equal the library, or to achieve their own recursive comparison algorithm.

Explain the difference between the ES5 and ES6 it?

Difficulty: Moderate

  • ECMAScript 5 (ES5): ECMAScript 5th edition, standardized in 2009. This standard has been fully implemented in all modern browsers.
  • ECMAScript 6 (ES6) or ECMAScript 2015 (ES2015): 6th Edition ECMAScript, standardized in 2015. This standard has been partially implemented in most modern browsers.

Specific can see the teacher's blog Ruan Yifeng

What Javascript in "closure" Yes? for example?

Difficulty: Moderate

Closure is a function of another function (called the parent function) is defined, and can be accessed in the declaration parent function definitions and scope.

Closures can access the variable three scopes:

  • In the variable declaration of its own scope;
  • Variables declared in the parent function;
  • In the variable declaration of global scope.

Example: to achieve image stabilization function expansion ||

How to Create private variables in JavaScript?

Difficulty: Moderate

To create a private variable can not be modified in JavaScript, you need to create it as a function of local variables. Even if this function is called, you can not access the variable outside the function. E.g:

function func() {
  var priv = "secret code";
}

console.log(priv); // throws error

To access this variable, we need to create a return to the auxiliary function private variables.

function func() {
  var priv = "secret code";
  return function() {
    return priv;
  }
}

var getPriv = func();
console.log(getPriv()); // => secret code

Please explain prototyping mode.

Difficulty: Moderate

Prototype model can be used to create a new object, but it is not the creation of a non-initialized object, but using the prototype object (or sample object) of the value of the object is initialized. Prototype mode is also called attributes mode.

Prototype mode is useful when initializing the business object, and the value of the default value database objects match the business. The default value prototype object is copied to a newly created business object.

The classic programming language rarely used the prototype model, but as a prototype JavaScript language in the construction of a new object and its prototype when using this mode.

Determining whether a given string is isomorphic.

Difficulty: Moderate

If the two strings are isomorphic, then the string of all characters appearing in A can be replaced by another character, to obtain a string B, and the sequence of characters must be retained. A string corresponding to each character must be one of each character string B.

  • paper and title will return true.
  • egg and sad returns false.
  • dgg and add returns true.
isIsomorphic("egg", 'add'); // true
isIsomorphic("paper", 'title'); // true
isIsomorphic("kick", 'side'); // false

function isIsomorphic(firstString, secondString) {

  // 检查长度是否相等,如果不相等, 它们不可能是同构的
  if (firstString.length !== secondString.length) return false

  var letterMap = {};

  for (var i = 0; i < firstString.length; i++) {
    var letterA = firstString[i],
        letterB = secondString[i];

    // 如果 letterA 不存在, 创建一个 map,并将 letterB 赋值给它
    if (letterMap[letterA] === undefined) {
      letterMap[letterA] = letterB;
    } else if (letterMap[letterA] !== letterB) {
      // 如果 letterA 在 map 中已存在, 但不是与 letterB 对应,
      // 那么这意味着 letterA 与多个字符相对应。
      return false;
    }
  }
  // 迭代完毕,如果满足条件,那么返回 true。
  // 它们是同构的。
  return true;
}

"Transpiling" What do you mean?

Difficulty: Moderate

For the newly added language syntax, can not be polyfill. Therefore, a better approach is to use a tool that can be converted to equivalent code older than the new code. This process is commonly known as a transform (transpiling), is transforming + compiling meaning.

Typically, you will converter (transpiler) was added to the build process, or similar linter minifier. There are many great converter selectable:

  • Babel: The ES6 + converted to ES5
  • Traceur: The ES6, ES7 converted to ES5

What is the principle "this" keyword is? Please provide some code examples.

Difficulty: Moderate

In JavaScript, this is how much of the function performed by the "owner" or, more precisely, refers to the object as a function of the current method.

function foo() {
    console.log( this.bar );
}

var bar = "global";

var obj1 = {
    bar: "obj1",
    foo: foo
};

var obj2 = {
    bar: "obj2"
};

foo();             // "global"
obj1.foo();        // "obj1"
foo.call( obj2 );  // "obj2"
new foo();         // undefined

How to add a custom method to the Array object, so you can run the following code?

Difficulty: Moderate

var arr = [1, 2, 3, 4, 5];
var avg = arr.average();
console.log(avg);

JavaScript is not class-based, but it is a prototype-based language. This means that each object is linked to another object (ie, the prototype object), inherited prototype object and method. You can keep track of each object's prototype chain until it reaches the prototype is not null object. We need to add a method to the global Array object by modifying the Array prototype.

Array.prototype.average = function() {
  // 计算 sum 的值
  var sum = this.reduce(function(prev, cur) { return prev + cur; });
  // 将 sum 除以元素个数并返回
  return sum / this.length;
}

var arr = [1, 2, 3, 4, 5];
var avg = arr.average();
console.log(avg); // => 3

What is the result of the following code output is?

Difficulty: Moderate

0.1 + 0.2 === 0.3

Output of this code is false, which is caused by an internal float. 0.1 + 0.2 is not exactly equal to 0.3, the actual result is .30000000000000004. One solution to this problem is the result rounded when decimal arithmetic operations.

Why write key component in write React / Vue project, what is its role?

Difficulty: Moderate

The key role is to quickly find the corresponding node in the diff algorithm execution speed increase diff.

vue diff algorithms are based on and react to compare the old and new virtual nodes to update nodes. In vue of diff function. We can first look diff algorithms.

In contrast, when crossing, when the head and tail of the old node with the new node when there is no cross-comparison of the results will compare to the old node key array according to a new node key, to find the corresponding old node (here corresponds to a key => the index map map). If you do not find it that is a new node. And if there is no key, it will adopt a way of traversing looking to find old node corresponding. One kind of mapping a map, the other is traversed to find. in comparison. Speed ​​map map faster.

Part Source vue follows:

// vue 项目  src/core/vdom/patch.js  -488 行
// oldCh 是一个旧虚拟节点数组,
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
       idxInOld = isDef(newStartVnode.key)
         ? oldKeyToIdx[newStartVnode.key]
         : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx)

Create a map function:

function createKeyToOldIdx (children, beginIdx, endIdx) {
 let i, key
 const map = {}
 for (i = beginIdx; i <= endIdx; ++i) {
   key = children[i].key
   if (isDef(key)) map[key] = i
 }
 return map
}

Traversal looking for:

// sameVnode 是对比新旧节点是否相同的函数
function findIdxInOld (node, oldCh, start, end) {
   for (let i = start; i < end; i++) {
     const c = oldCh[i]

     if (isDef(c) && sameVnode(node, c)) return i
   }
}

Analytical [ '1', '2', '3']. Map (parseInt)

Difficulty: Moderate

At first glance this topic when, out of my mind the answer is [1, 2, 3], but the real answer is [1, NaN, NaN].

First, let us recall that the first parameter callback map function:

  var new_array = arr.map(function callback(currentValue[, index[, array]]) { // Return element for new_array }[, thisArg])

This callback can receive a total of three parameters

  • Wherein the first parameter representing the current element is processed, and the second parameter represents the index of the element.
  • ParseInt is used to parse the string, character string specified base to become an integer.
  • parseInt (string, radix) receives two parameters, a first representative value (character string) to be treated, expressed as the second base resolved.

After understanding these two functions, we can simulate what the operation;

  • When parseInt ( '1', 0) // radix is ​​0, and the parameter string is not with "0x" and "0" at the beginning, in accordance with the process 10 as the base. This time returns 1;
  • parseInt ( '2', 1) // base is 1 (binary 1) numbers, the maximum value is less than 2, it can not be resolved, returns NaN3;
  • parseInt number represented by (3 '', 2) // base 2 (binary), the maximum value is less than 3, it can not be resolved, returns NaN.

map function returns an array, so the final result is [1, NaN, NaN].

What is image stabilization and throttling? What's the difference? How to achieve?

Difficulty: Moderate

Shake

After the high-frequency trigger events within n seconds function only once, if n seconds high frequency event is triggered again, the re-calculation time;

Idea: Every time trigger events are canceled delay before calling the method:

Beggar edition:

function debounce(fn) {
  let timeout = null; // 创建一个标记用来存放定时器的返回值
  return function () {
    clearTimeout(timeout); // 每当用户输入的时候把前一个 setTimeout clear 掉
    timeout = setTimeout(() => { 
      // 然后又创建一个新的 setTimeout
      // 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 fn 函数
      fn.apply(this, arguments);
    }, 500);
  };
}
function sayHi() {
  console.log('防抖成功');
}

var inp = document.getElementById('inp');
inp.addEventListener('input', debounce(sayHi)); // 防抖
Throttling

High-frequency event is triggered, but only once within n seconds, it will dilute the throttle perform a function of frequency.

Ideas: every judge whether there is a trigger event delay function currently awaiting execution.

Beggar edition:

function throttle(fn) {
  let canRun = true; // 通过闭包保存一个标记
  return function () {
    if (!canRun) return; // 在函数开头判断标记是否为 true,不为 true 则 return
    canRun = false; // 立即设置为 false
    setTimeout(() => { // 将外部传入的函数的执行放在 setTimeout 中
      fn.apply(this, arguments);
      // 最后在 setTimeout 执行完毕后再把标记设置为 true(关键) 表示可以执行下一次循环了
      // 当定时器没有执行的时候标记永远是 false,在开头被 return 掉
      canRun = true;
    }, 500);
  };
}
function sayHi(e) {
  console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));

Introduced to distinguish Set, Map, WeakSet and WeakMap of?

Difficulty: Moderate

Set

  • The only member of the disorder is not repeated;
  • [Value, value], the key is consistent with the key name (or the only key, no key name);
  • You can traversal methods: add, delete, has.

WeakSet

  • Members are subject;
  • Members are weak references, can be recycled garbage collection mechanism can be used to save the DOM node, it is not likely to cause a memory leak;
  • You can not traverse, methods add, delete, has.

Map

  • Is a collection of key-value pairs essentially similar set;
  • Can traverse, many ways, can be converted with a variety of data formats.

WeakMap

  • Accepts only objects of most keys (except the null), does not accept the values ​​of other types as keys;
  • Keys are weak references, may be any key, key pointed objects may be garbage collected, then the key name is invalid;
  • Can not traverse, methods get, set, has, delete.

Introduced to the depth-first traversal and breadth-first traversal, how?

Difficulty: Moderate

Depth-first traversal (DFS)

Depth-first traversal (Depth-First-Search), is a search algorithm, traversing the tree node depth along its tree, as far as the search tree branch. When all the edges have been exploring node v over the piece back to the originating node discovery edge node v. This process continues until the source node have been discovered to date all other nodes, if there are undetected nodes, wherein a node is selected as a source node and undiscovered Repeat until all nodes are exploring completed.

Simply put, DFS is that the blame should start from a node in the graph until the last node, then go back and continue to the next path is traced until it reaches all the nodes, and so forth, until there is no path.

DFS may be generated corresponding to FIG topological sorting table, the topological sort table can solve many problems, such as maximum path problem. Usually heap data structure used to assist in achieving DFS algorithm.

Note: The depth of the DFS belong blind search, search is no guarantee that the path is the shortest path, nor is it in the search for a specific route, but through a search to see what path the figure can be selected.

step:

  • Access vertices v;
  • Sequentially from the adjacent node is not accessible v, and depth-first traversal of FIG.; And v have the figures until the communication path vertices have been visited;
  • If this time is not the way to access the apex there, it has not been accessed from a vertex of view, re-depth-first traversal until all vertices are visited so far.

achieve

Graph.prototype.dfs = function() {
   var marked = []
   for (var i=0; i<this.vertices.length; i++) {
       if (!marked[this.vertices[i]]) {
           dfsVisit(this.vertices[i])
       }
   }

   function dfsVisit(u) {
       let edges = this.edges
       marked[u] = true
       console.log(u)
       var neighbors = edges.get(u)
       for (var i=0; i<neighbors.length; i++) {
           var w = neighbors[i]
           if (!marked[w]) {
               dfsVisit(w)
           }
       }
   }
}
Breadth-first traversal (BFS)

Breadth first traversal (Breadth-First-Search) are starting from the root, traversing the nodes of the graph along the width, if all the nodes are visited, the algorithm terminates, also belong to the BFS search blindly, the general queue data structure used to assist in achieving BFS.

BFS start from a node, try to access as much as possible close to its destination node. Essentially this traversal in FIG moved layer by layer, the first layer closest to the first check node, and then gradually moves down to the layer farthest from the originating node.

step:

  • Create a queue and start node in a queue;
  • If the queue is not empty, the queue removed from the first node, and detects whether it is the destination node;
    • If the target node, the end of the search, and returns the result;
    • If not, then it has not been tested all bytes are added to the queue points;
  • If the queue is empty, not shown in the drawing and the destination node, traversal is terminated.

achieve

Graph.prototype.bfs = function(v) {
   var queue = [], marked = []
   marked[v] = true
   queue.push(v) // 添加到队尾
   while(queue.length > 0) {
       var s = queue.shift() // 从队首移除
       if (this.edges.has(s)) {
           console.log('visited vertex: ', s)
       }
       let neighbors = this.edges.get(s)
       for(let i=0;i<neighbors.length;i++) {
           var w = neighbors[i]
           if (!marked[w]) {
               marked[w] = true
               queue.push(w)
           }
       }
   }
}

Please write the operating results of the following code:

Difficulty: Moderate

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')

The nature of the subject, is to examine issues related to setTimeout, promise, implement and execute the order async await, and the JS event loop.

answer

script start
async1 start
async2
promise1
script end
async1 end
promise2
settimeout

The array of flattening and removing wherein duplicate data to finally obtain a non-repeating array in ascending

Difficulty: Moderate

Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})

JS asynchronous solution development as well as the advantages and disadvantages

Difficulty: Moderate

Callback function (callback)
setTimeout(() => {
   // callback 函数体
}, 1000)

Disadvantages: callback hell, can not catch the error with a try catch, can not return

The fundamental problem is that the callback hell:

  • Lack of order: commissioning difficulties caused by the callback hell, and way of thinking of the brain do not match;
  • Coupling the presence of nested functions, once subject to change, it will indeed affect the whole body, i.e., (reverse control);
  • Nested function too much, difficult to handle errors.
ajax('XXX1', () => {
   // callback 函数体
   ajax('XXX2', () => {
       // callback 函数体
       ajax('XXX3', () => {
           // callback 函数体
       })
   })
})
Promise

Promise is to solve problems arising callback.

Promise to achieve a chained calls, that are then returned each time after a new Promise, then if we return in the, return the result will be Promise.resolve () package.

Advantages: solve the problem of callback hell.

ajax('XXX1')
 .then(res => {
     // 操作逻辑
     return ajax('XXX2')
 }).then(res => {
     // 操作逻辑
     return ajax('XXX3')
 }).then(res => {
     // 操作逻辑
 })
Generator

Features: You can control the execution of the function, it can be used with co.js library use. (That is, koa early use of the library)

function *fetch() {
   yield ajax('XXX1', () => {})
   yield ajax('XXX2', () => {})
   yield ajax('XXX3', () => {})
}
let it = fetch()
let result1 = it.next()
let result2 = it.next()
let result3 = it.next()
Async/await

async, await the ultimate solution is asynchronous.

Advantages are: the code is clear, then do not write a lot like the Promise chain, addressed the issue of callback hell;

Disadvantage: await asynchronous code transformed into the synchronization code, if a plurality of asynchronous operation without dependency on the use await will lead to lower performance.

async function test() {
 // 以下代码没有依赖性的话,完全可以使用 Promise.all 的方式
 // 如果有依赖性的话,其实就是解决回调地狱的例子了
 await fetch('XXX1')
 await fetch('XXX2')
 await fetch('XXX3')
}

The following example uses await a look:

let a = 0
let b = async () => {
 a = a + await 10
 console.log('2', a) // -> '2' 10
}
b()
a++
console.log('1', a) // -> '1' 1

The above mentioned internal await explanation achieve a generator, in fact, it is the generator coupled with await syntactic sugar Promise, and the internal implementation of the automatic execution generator. If you are familiar with co it, in fact, you can achieve this syntax sugar.

At last

  1. Just do not like is the point of bullying !!!
  2. Welcome to public concern number "front-end Advanced Course" seriously study the front, advanced together.

Guess you like

Origin www.cnblogs.com/zhongmeizhi/p/12463415.html