[Recommended collection] 2021 front-end school recruits BATJ interview cheats, escort you gold three silver four, direct access to major factories!

This article is mainly about basic interview questions in javascript and css. It is suitable for review and consumption before the interview and usually.

Basic knowledge must be asked on the front-end side. If you are overwhelmed by the basic knowledge, even if you play with the framework, no matter how well webpack, git, and node learn, it will not help, because the other party will not give you the opportunity to show it. , Don’t miss your favorite company because of the foundation. The basic knowledge of the front-end is complicated and many, it is not ok to understand, some are really to be remembered. Of course, we are the front-end engineers of Niu X. It is not necessary to memorize knowledge points like English words every day. As long as we pay more attention to the summary in our work, we can just brush the questions at the front end of the interview.

what? You asked me for a good interview question essay, isn’t this right in front of your eyes?

javascript articles

One, data type

There are several types of JavaScript

  • Basic data types: undefined, null, boolean, number, string, symbol (new data type of es6)
  • Reference data types: object, array, function (collectively called object)

Data type detection

typeof For basic data types, in addition to the  null correct type, typeof for objects, except for functions, will display objec

typeof 5 // 'number'
typeof '5' // 'string'
typeof undefined // 'undefined'
typeof false// 'boolean'
typeof Symbol() // 'symbol'
console.log(typeof null)  //object
console.log(typeof NaN)   //number

typeof [] // 'object'
typeof {} // 'object'
typeof console.log // 'function'

instanceofJudge the data type through the prototype chain

p1 = new Person()
p1 instanceof Person // true

Object.prototype.toString.call() can detect all data types, which is a perfect method.

var obj={}
var arr=[]
console.log(Object.prototype.toString.call(obj))    //[object Object]
console.log(Object.prototype.toString.call(arr))    //[object Array]

Deep copy

Shallow copy

Object.assign()    //es6的方法

Object.assign will merge objects to generate a new object. If the property of the object is that the new object will not change after the normal type is changed, if the reference type is changed, the new object will also change, so Object.assign is actually a shallow copy.

var obj={aa:1,b:{item:'45'}};
var newObj=Object.assign({},obj);
obj.aa=2;
obj.b.item='kk';
console.log(newObj.aa);        //1
console.log(newObj.b.item);    //kk

Deep copy

JSON.parse(JSON.stringify(obj))

Use JSON.stringify(obj) to convert the object to a json string first, and then JSON.parse() to convert it back to a json object to achieve deep copy, which is also a commonly used method.

Implement a deep copy with js

In fact, the deep copy can be divided into 2 steps, shallow copy + recursion. When shallow copying, it is judged whether the attribute value is an object. If it is an object, the recursive operation is performed, and the two are combined to achieve deep copy.

  function cloneDeep(source) {
      if (!isObject(source)) return source; // 非对象返回自身
      var target = Array.isArray(source) ? [] : {};
      for (var key in source) {
        if (source.hasOwnProperty(i)) {
          if (isObject(source[key])) {
            target[key] = cloneDeep(source[key]); // 注意这里
          } else {
            target[key] = source[key];
          }
        }
      }
      return target;
    }
    function isObject(obj) {
      return typeof obj === 'object' && obj != null;
    }

Two, scope

Variable declaration promotion

  • In JavaScript, function declarations (function aa(){}) and variable declarations (var) are often implicitly promoted to the top of the current scope by the JavaScript engine.
  • The priority of the function declaration is higher than the variable. If the variable name is the same as the function name and is not assigned, the function declaration will override the variable declaration
  • The assignment part in the declaration statement will not be promoted, only the name of the variable will be promoted

Scope chain

Because the nesting of functions forms a hierarchical relationship of scope. When the function is executed, the search starts from the current scope, and the variable that is not found will be searched in the upper scope until the global function, which is the scope chain.

  • In JavaScript, the scope is the area within function(){}, which is called function scope.
  • The global function cannot view the internal details of the local function, but the local function can view the details of the function above it, up to the global details

Closure

The principle of closure is the scope chain. There is a function G inside function F. Function G can access the variables in function F, then function G is a closure.

   function F() {
      let a = 1
      window.G = function () {
        console.log(a)
      }
    }
    F()
    G() // 1

Three, prototype and inheritance

js several ways to create objects

Object literal square

var obj={};

new a constructor

function Pel(){}
    var p=new Pel();
    p.name="hu";
    p.age="25";
    p.address=function(){
 }

new a built-in pair

var obj=new Object();

Object.create() creates an object

var test = Object.create({x:1});

Leave a question for everyone, new Object(), Object.create(), {}, what is the difference between these three ways to create objects.

How JS implements a class

Constructor method

Disadvantages: This and prototype are used, the writing is complicated, and the readability is poor

function P(name, age){
     this.name = name;
     this.age= age;
   }
   P.prototype.sal= function(){

   }
   var pel= new P("jj", 1);
   pel.sell()

ES6 syntactic sugar class

class Point {
       constructor(x, y) {
         this.x = x;
         this.y = y;
       }
       toString() {
         return '(' + this.x + ', ' + this.y + ')';
       }
     }
  var point = new Point(2, 3);

Prototype chain

One sentence analysis of what is the prototype chain

When traversing the properties of a real column, first traverse the properties on the real column object, then traverse its prototype object, and traverse to Object

Any class (function) has a prototype object, which has at least two properties (constructor, proto ). The constructor points to the function itself, and proto points to the parent prototype object.

There is a prototype property on the function, which points to the prototype object, through which the prototype object can be accessed

The real column of the function can directly access the prototype object (because there is proto on the real column pointing to the prototype object of the constructor)

function Dog(){}        //类         
var obj=new Dog();      //实列
obj.name='沪江';
Dog.prototype.name="旺财";
Dog.prototype.eat=function(){
    console.log(this.name);
};
console.log(Dog.prototype.name);  //旺财
console.log(obj.prototype);      //undefined,prototype是类上才有的,实列上没有
obj.eat();                       //沪江(先遍历实列对象上的属性,再遍历它的原型对象)

inherit

How does Js implement inheritance?

Constructor binding: Use the call or apply method to bind the constructor of the parent object to the child object

function Cat(name,color){
  Animal.apply(this, arguments);
  this.name = name;
  this.color = color;
}

Instance inheritance: point the prototype of the child object to an instance of the parent object

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

Copy inheritance: If you copy all the properties and methods of the parent object into the child object

function extend(Child, Parent) {
   var p = Parent.prototype;
   var c = Child.prototype;
   for (var i in p) {
      c[i] = p[i];
   }
   c.uber = p;
}

Prototype inheritance: point the prototype of the child object to the prototype of the parent object

function extend(Child, Parent) {
    var F = function(){};
     F.prototype = Parent.prototype;
     Child.prototype = new F();
     Child.prototype.constructor = Child;
     Child.uber = Parent.prototype;
}

ES6 syntactic sugar extends inheritance

class ColorPoint extends Point {
    constructor(x, y, color) {
        super(x, y); // 调用父类的constructor(x, y)
        this.color = color;
    }
    toString() {
        return this.color + ' ' + super.toString(); // 调用父类的toString()
    }
}

❤️The space is limited, for more detailed content, click me to get the full version pdf to view❤️

Four, new and this

What exactly does the new operator do?

When we new a piece of data, what exactly does the new operator do?

  • The first is to create an instance object {}
  • The this variable refers to the object and also inherits the prototype of the constructor
  • Second, attributes and methods are added to the object referenced by this
  • And the newly created object is referenced by this, and finally returns this implicitly

Simulation implementation of new

function objectFactory() {

    var obj = new Object(),//从Object.prototype上克隆一个对象

    Constructor = [].shift.call(arguments);//取得外部传入的构造器

    var F=function(){};
    F.prototype= Constructor.prototype;
    obj=new F();//指向正确的原型

    var ret = Constructor.apply(obj, arguments);//借用外部传入的构造器给obj设置属性

    return typeof ret === 'object' ? ret : obj;//确保构造器总是返回一个对象

};

Understanding of this object

Ordinary function

  • this always refers to the direct caller of the function
  • If there is a new keyword, this points to the instance object from new
  • In the event, this points to the object that triggered the event
  • This in attachEvent under IE always points to the global object Window
  • In the arrow function, the this object in the function body is the object of the scope when it is defined, not the object of the scope when it is used.
function foo() {
  console.log(this.a)
}
var a = 1
foo()           //1       
​
const obj = {
  a: 2,
  foo: foo
}
obj.foo()      //2
​
const c = new foo()   //undefined

  • For directly calling foo, no matter where the foo function is placed, this must be window
  • For obj.foo(), we only need to remember that whoever calls the function is this, so in this scenario, this in the foo function is the obj object
  • For the new method, this is always bound to the new object, and this will not be changed in any way

After talking about the above situations, in fact, there should be no problem with this in many codes. Let us look at this in the arrow function.

function a() {
  return () => {
    return () => {
      console.log(this)
    }
  }
}
a()()()        //Window

  • First of all, the arrow function does not have this. The this in the arrow function depends only on the this of the first ordinary function that wraps the arrow function. In this example, because the first ordinary function that wraps the arrow function is a, this is window. In addition, it is invalid to use bind functions for arrow functions.

五、apply、call、bind

call, applyAnd bindare Functionthe three methods that the object comes with, all for changing the internal this direction of the function body  .
apply 、 call 、bind The first parameter of the three is  this the object to be pointed to, that is, the context that you want to specify;
apply 、 call 、bind all three can use subsequent parameters to pass parameters;
bind returns the corresponding  function , which is convenient for later calling; apply 、call it is called immediately.

function fruits() {}

fruits.prototype = {
	color: 'red',
	say: function() {
		console.log(this.color);
	}
};

var apple = new fruits();

apple.say();   // red, 此时方法里面的this 指的是fruits

banana = {color: 'yellow'};
apple.say.call(banana); //yellow,此时的this的指向已经通过call()方法改变了,指向的是banana,this.color就是banana.color='yellow';

apple.say.apply(banana);//yellow,同理,此时的this的指向已经通过apply()方法改变了,指向的是banana,this.color就是banana.color ='yellow';

apple.say.apply(null); //undefined, null是window下的,此时,this 就指向了window ,但是window下并没有clolr这个属性,因此this.clolr就是window.color=undefined;

call incoming parameter list
apply incoming array

var array1 = [12,'foo'];
var array2 = ['Doe',100];

Array.prototype.push.call(array1, 'Doe',100)
Array.prototype.push.apply(array1, array2)

The bind() method will create a new function. When this new function is called, the new function will use the first parameter passed in the bind() method when creating it as this, and pass the second and later parameters of the bind() method. The parameters of, plus the parameters of the binding function when it is running, are used as the parameters of the original function in order to call the original function.

var bar = function(){
	console.log(this.x);
};
var foo = {
	x:3
};
bar();    // undefined
var func = bar.bind(foo); 

func(); // 3

Six, data processing

Array deduplication

var arr=['12','32','89','12','12','78','12','32'];
    // 最简单数组去重法
    function unique1(array){
        var n = []; //一个新的临时数组
        for(var i = 0; i < array.length; i++){ //遍历当前数组
            if (n.indexOf(array[i]) == -1)
                n.push(array[i]);
        }
        return n;
    }
    arr=unique1(arr);

Sort

/**
	 * 按 sort 及  id 排序
	 * @param {Object} a
	 * @param {Object} b
	 */
 function   sortFun(a, b) {
       return a.sort - b.sort == 0 ? a.id - b.id : a.sort - b.sort
  };
 arr.sort(sortFun)   //从小到大排序

Recursive sum

    function add(num1,num2){
	var num = num1+num2;
		if(num2+1>100){
		   return num;
	         }else{
	            return add(num,num2+1)
	        }		   	
     }
     var sum =add(1,2)

Count the number of repetitions of items in the array

var arr=['胡将','胡将','hujiang','胡将','胡江','hujiang'];
var obj={};
arr.sort();    //先排序
for(var i=0;i<arr.length;){
	var con=0;
	for(var j=i;j<arr.length;j++){
		if(arr[i]===arr[j]){
			con++
		}
	}
	obj[arr[i]]=con; 
	i=i+con;    //跳过重复的值
}
console.log(obj);  //{ hujiang: 2, '胡将': 3, '胡江': 1 }

七、Event Loop

Macro task/micro task

In addition to generalized synchronous tasks and asynchronous tasks, we have a more refined definition of tasks:

  1. Macro-task (macro task): The task executed in the current call stack is called a macro task. Including: script all code, setTimeout, setInterval, setImmediate (not supported by the browser for the time being, only supported by IE10, see MDN for details ), I/O, UI Rendering.
  2. .micro-task (micro task): The current (in this event loop) macro task is executed, the task that needs to be executed before the next macro task starts is a micro task. Including: Process.nextTick (only for Node), Promise, Object.observe (obsolete), MutationObserver
  3. Different types of tasks will enter the corresponding Event Queue. The events in the macro task are placed in the callback queue and maintained by the event-triggered thread; the events of the micro task are placed in the micro task queue and maintained by the js engine thread.

What is event loop in one sentence analysis

  • When the main thread is running, a heap and stack are generated;
  • js parses the method from top to bottom, and arranges the synchronization tasks in the execution stack in the order of execution;
  • When the program calls an external API (such as ajax, setTimeout, etc.), such asynchronous tasks will be suspended, and the tasks in the execution stack will continue. After the asynchronous task returns the result, it is arranged in the event queue in order;
  • The main thread first clears the synchronous tasks in the execution stack, and then checks whether there are tasks in the event queue. If so, pushes the callback corresponding to the first event to the execution stack for execution. If an asynchronous task is encountered during execution, Then continue to arrange this asynchronous task into the event queue.
  • Every time the main thread empties the execution stack, it goes to the event queue to check whether there are tasks. If so, it takes one out and pushes it to the execution stack for execution each time. This cyclical process is called "Event Loop Event Loop"

❤️The space is limited, for more detailed content, click me to get the full version pdf to view❤️

8. Browser page rendering process

The general process of browser rendering page:

1. The browser parses the html source code, and then creates a DOM tree. Parallel request css/image/js In the DOM tree, each HTML tag has a corresponding node, and each text will also have a corresponding text node. The root node of the DOM tree is documentElement, which corresponds to the html tag.

2. The browser parses the CSS code and calculates the final style data. Build the CSSOM tree. It will directly ignore the illegal syntax in the CSS code. When parsing CSS, priority will be defined in the following order: browser default settings <user settings <external link style <inline style <style in html.

3. DOM Tree + CSSOM --> rendering tree (rendering tree). The render tree is a bit similar to the DOM tree, but there are differences.

The DOM tree has a one-to-one correspondence with the html tags, but the render tree will ignore elements that do not need to be rendered, such as head and display: none elements. And each line in a large section of text is an independent node in the render tree. Each node in the render tree stores corresponding css attributes.

4. Once the render tree is created, the browser can directly draw the page to the screen according to the render tree.

The above four steps are not completed in one order. If the DOM or CSSOM is modified, the above process will be repeated. In fact, CSS and JavaScript tend to modify the DOM or CSSOM multiple times.

Nine, browser cache

This piece of content is usually asked about strong caching and negotiation caching in interviews . For more detailed content, click me to get the full version pdf to view

css

One, the box model

The composition of the box model, from inside to outside content, padding, border, margin.

In the IE box model, width represents the width of the three parts of content+padding+border

In the standard box model, width refers to the width of the content part

Use of box-sizing

box-sizing: content-box 是W3C盒子模型
  box-sizing: border-box 是IE盒子模型

The default attribute of box-sizing is content-box

Two, centered

Center horizontally

  • Elements in the line: text-align: center
  • Block-level elements: margin: 0 auto
  • position:absolute +left:50%+ transform:translateX(-50%)
  • display:flex + justify-content: center

Vertically centered

  • Set line-height equal to height
  • position:absolute +top:50%+ transform:translateY(-50%)
  • display:flex + align-items: center
  • display:table+display:table-cell + vertical-align: middle;

//Don't know the width and height

  width: 78px;
  height: 78px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);

//Know the width and height

        height: 100px;
        width: 100px;
        position: absolute;
        left:50%;
        top: 50%;
        margin-left: -50px;
        margin-top: -50px;
        display:flex;
        justify-content: center;
        align-content: center;

Written at the end:

The interview is a two-way selection process. When we interview, we should not think of ourselves as a selected vulnerable person. There are many front-end knowledge, sometimes the interview results are not ideal, don't doubt yourself. It's just that I still have some shortcomings, so I can make up for it later. We are not asking someone to give us a job, we are just looking for a company that suits us. Don't be arrogant or conceited. If you organize your mindset, you will definitely find a company that suits you! ! ! Come on

The front-end knowledge points are complex and numerous, and need to be continuously summarized in the learning process. . .

Guess you like

Origin blog.csdn.net/pig_html/article/details/112909883