CSS styles

What are the selectors of the CSS

1) Id selector (# myID)

2) Class selector (.myClass)

3) Tag selector (div, H1, P)

4) Adjacent sibling selector (H1 + P)

5) Descendant selector (UL > LI)

6) Descendant selector (Li A)

7) Global selector (*)

8) Attribute selector (a[rel=”external”])

9) Pseudoclass selector (A: hover, Li: nth-child)

What are the differences between block elements and inline elements? How do I convert them to each other

The display attribute is used to distinguish block-level elements from inline elements, with block representing block-level elements and inline representing inline elements. Block level elements: 1. Content is a single line. 2. Width and height can be set. Margin and padding can also be set. Inline elements: 1. Content does not occupy a single line. 2, width is supported by the content and cannot be set. 3. Marigin and padding cannot be set in the vertical direction, but can be set in the horizontal direction. 4. If there are multiple inline elements, they will be arranged in a row until the parent container cannot fit them. Block-level elements and inline elements can be switched with each other by modifying the display attribute.

What are the common UI components

How does CSS center an element horizontally and vertically

<div class="par">
    <div class="child"></div>
</div>
Copy the code

1. Elastic box

    .par{
        width: 600px;
        height: 600px;
        background-color: red;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .child{
        width: 200px;
        height: 200px;
        background-color: pink;
    }
Copy the code

2, absolute positioning

 .par{
        width: 600px;
        height: 600px;
        background-color: red;
        position: relative;
    }
    .child{
        width: 200px;
        height: 200px;
        background-color: pink;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-left: -100px;
        margin-top: -100px;
    }
Copy the code

3. Table method

.par{
        width: 600px;
        height: 600px;
        background-color: red;
        display: table-cell;
        vertical-align: middle;
    }
    .child{
        width: 200px;
        height: 200px;
        background-color: pink;
        margin: 0 auto;
    }
Copy the code

4. Margin calculation

.par{
        width: 600px;
        height: 600px;
        background-color: red;
        overflow: hidden;
    }
    .child{
        width: 200px;
        height: 200px;
        background-color: pink;
        margin: 200px auto;
    }
Copy the code

New elements for HTML5

First of all, in order to better practice web semantics, HTML5 adds header, footer, nav,aside,section and other semantic tags. In terms of forms, in order to enhance forms, it adds color, emial,data,range and other types to input. In terms of storage, Provides sessionStorage, localStorage, and offline storage, through these storage methods to facilitate data storage and access to the client, in the multimedia aspect of audio and video elements Audio and vedio, in addition to geographical positioning, Canvas canvas, drag and drop, Multithreaded programming of Web worker and Websocket protocol

javascript

Code Practice 01

	var scope = 'glo';
	function fn(params) {
	    console.log("01",scope);
	    var scope = "local";
	    console.log(".",scope);
	}
	fn();
Copy the code

! Practice results 01] [code (/ Users/jing/Library/Application Support/typora – user – images/image – 20210222133711564. The PNG)

Code Practice 02

for (let i = 0; i < 5; i++) {
	(function(i){
		setTimeout(function(){
			console.log("3",i);
		})
	})(1000*i);
}
Copy the code

! [image-20210222134322713](/Users/jing/Library/Application Support/typora-user-images/image-20210222134322713.png)

The algorithm that counts the most characters in a string

var str = 'abdgdbca';
	function fn(str){
		let dic = {};
		for (var i =  0; i < str.length; i++) {
			if(dic[str[i]]){
				dic[str[i]]++;
			}else {
				dic[str[i]] = 1; }}console.log("04",dic);
	}
	fn(str);
Copy the code

! [image-20210222140057880](/Users/jing/Library/Application Support/typora-user-images/image-20210222140057880.png)

Implementation of digit thousands separator ***

function numFormat(num){
    num=num.toString().split(".");  // Separate the decimal points
    var arr=num[0].split("").reverse();  // Convert to an array of characters and sort in reverse order
    var res=[];
    for(var i=0,len=arr.length; i<len; i++){if(i%3= = =0&&i! = =0){
         res.push(",");   // Add a delimiter
      }
      res.push(arr[i]);
    }
    res.reverse(); // Reverse order again to make the correct order
    if(num[1]) {// Add decimals if there are decimals
      res=res.join("").concat("."+num[1]);
    }else{
      res=res.join("");
    }
    return res;
}

var a=1234567894532;
var b=673439.4542;
console.log(numFormat(a)); / / "1234567894532"
console.log(numFormat(b)); / / "673439454"
Copy the code

Parses the URL object and returns the associated parameter names and parameter values

function sys_getUrlkey(url) {
  var params = {};
  try{
    var urls = url.split("?");                  
    console.log('1 _ segmentation url:, urls)
    var arr = urls[1].split("&");               
    console.log(' '2 _ segmentation urls [1]., arr)
    for (var i = 0, l = arr.length; i < l; i++) {
      var a = arr[i].split("=");                
      console.log('3_ traverse arr and divide it and assign it to a:', a[0], a[1])
      params[a[0]] = a[1];                      
      console.log('4_a assigns a value to params :', params)
    }
                                            
    console.log('5 _ results:, params)
  }catch(e){}
  return params;
}
Copy the code

Gives an array and inserts the specified element into the array at the specified position

Var elementy = [3,4,5,7,8,21,32,22,2]; Var index = 6; // Insert the value of the index myarr.splice (index, 0, elementy);Copy the code

Gives the specified time and calculates the total number of days remaining until the specified time

var eneTime = new Data("2019/8/7")
Copy the code

Gets all attribute values and concatenates them into strings

var person = {fname:'john'.age:18}
var str = "";
for(let key in person){
    str+=key+'='+ person[key]+","; 
}
console.log(str.substring(0,str.length-1));
// fname=john,age=18
Copy the code

Implement a debounce function using setTimeout

function debounce(fn, delay) {
  let timer
  return function(. args) {
    if (timer) clearTimeout(timer)
    // Use the arrow function to handle this problem
    timer = setTimeout(() = > fn.apply(this, args), delay)
  }
}
Copy the code

closure

In a nutshell, a closure is a function that can read variables inside other functions, or a child function that is called outside the scope of the parent function.

What are closures and why are they used?

A closure is a function that has the right to access variables in the scope of another function. The most common way to create a closure is to create another function within a function and access local variables of this function through another function. Closures can be used to break through the scope domain and pass variables and methods inside the function to the outside.

Method A nested method B wants to call b’s variable and return that variable.

Function:

2. Parameters and variables are not collected by the garbage collection mechanism

What is a closure

The “official” explanation: a “closure” is an expression (usually a function) that has many variables and the environment to which they are bound, and thus the variables are part of that expression. In plain English, function B inside function A creates a closure when it is referenced by a variable outside of function A.

Closure features:

(1) Closure: The outside world cannot access the data inside a closure. If variables are declared inside a closure, the outside world cannot access them unless the closure actively provides an access interface to the outside world;

(2) Durability: for a common function, the system automatically cancels the function after it is called. For a closure, the closure structure is still stored in the external function after it is called.

Impact on the page:

Using closures will occupy memory resources, and excessive use of closures will lead to memory overflow.

function f1() {
  var n = 999;
  function f2() {
		console.log(n);
	}
  return f2;
}
var result = f1();
result(); / / 999
Copy the code

The closure is the function F2, which reads variables inside other functions

A closure is useful for reading variables inside a function and for keeping those variables in memory at all times.

Application:

  1. Local variables: Define local variables in a function that have shared meaning. Note: Global variables will pollute the outside world

  2. Inline functions: Function declarations have inline functions that access local variables in the function.

  3. External use: a function returns an embedded function from which an external can hold and access a local variable declared inside the function that is otherwise inaccessible.

Native JS manipulation of the DOM

methods describe
getElementById() Returns the element with the specified ID.
getElementsByTagName() Returns a node-list (collection/array of nodes) containing all elements with the specified label name.
getElementsByClassName() Returns a node list containing all elements with the specified class name.
appendChild() Adds a new child node to the specified node.
removeChild() Delete child nodes.
replaceChild() Replace the child node.
insertBefore() Inserts a new child node before the specified child node.
createAttribute() Create the properties node.
createElement() Create the element node.
createTextNode() Create a text node.
getAttribute() Returns the value of the specified property.
setAttribute() Sets or modifies the specified property to the specified value.

There are several differences between browser caches

Caches: localStore, cookie, session

localStore: Cookie: 4K cross-domain data is stored on the local browser (client) Insecure Session: Data is stored on the server. The time-sensitive end (occupies server resources when the number of accesses increases) Cookie and session have the following in common: Both sessions are used to track the identity of a browser user.

JavaScript prototype, prototype chain?

Everything is an object, and the prototype chain lookup is looking for the prototype of the owning constructor, hierarchy lookup, hierarchy inheritance, and the top level is NULL

! [image-20210301171512770](/Users/jing/Library/Application Support/typora-user-images/image-20210301171512770.png)

Stereotype: Defines properties and methods shared by all instance objects. It is a property of a function

JavaScript dictates that all objects have their own prototype object. On the one hand, any object can serve as a prototype for other objects. On the other hand, since a prototype object is also an object, it also has its own prototype. Therefore, there is a ‘prototype chain’ : object to prototype, prototype to prototype…

Prototype chain: Is a relationship between instance objects and prototype objects. The relationship is related by prototype (PROTO)

Js objects have a built-in property that points to their own prototype

####JavaScript prototype chain? What are the characteristics? (important)

  1. Every function in JS has a prototype object property called prototype. And the default prototype for all functions is an instance of Object.
  2. Every object that inherits a child of a parent function contains an internal attribute _proto_. This property contains a pointer to the prototype of the parent function. If the parent function’s prototype object has a _proto_ attribute that is one level up. In the process, a prototype chain is formed.
  3. The prototype chain implements inheritance. There are two problems with stereotype chains: A stereotype property that contains a reference type value is shared by all instances. B cannot pass arguments to the constructor of a supertype when creating a subtype.

JS to implement the array deduplication method

First, use Set to remove weight

/* 1. The return value is a deduplicated array. 2
var arr = ['one'.'two'.'three'.'one'.'three'.'two'.'four'];
let el = new Set(arr);
console.log(el); // ['one','two','three','four'];
Copy the code

IndexOf() and lastIndexOf()

/* indexOf: Search the target string from left to right to see if it contains Value; If yes, returns the first occurrence of the index; If not, return the same steps as lastIndexOf() : 1. Create an empty array to store the deleted data. 2. Check each item */ in the array
let arr = ['one'.'two'.'three'.'one'.'three'.'two'.'four'];
let indexArr = [];
arr.forEach(item= > {
   if(indexArr.indexOf(item)===-1){
      indexArr.push(item);
   };
});
console.log(indexArr); // ['one','two','three','four'];
Copy the code

Three, use filter to remove weight

let arr = ['one'.'two'.'three'.'one'.'three'.'two'.'four'];
let el = arr.filter((item,index) = >arr.indexOf(item)===index);
console.log(el); // ['one','two','three','four'];
Copy the code

Fourth, the use of object characteristics to remove weight

(1) Object methods and for loops

/* 1. Declare an object obj, using object properties 2. Loop through each item and use keys(values) to fetch the key */
var arr = ['one'.'two'.'three'.'one'.'three'.'two'.'four'];
var obj = {};
for(var i=0; i<arr.length; i++){ obj[arr[i]] = arr[i]; };var el =  Object.keys(obj);
console.log(el) // ['one','two','three','four'];
Copy the code

#### What is the difference between null, undefined, and undeclared variables? How are these state values checked and determined?

Variables that are declared but not initialized have a value of undefined. Variables that are not declared have a value of undefined using the typeof operator.

Null is an empty object reference. Undefined is a declared variable that has not been assigned a value. These two can be used to distinguish an empty object pointer from an uninitialized variable.

The undefined value is derived from the null value. So for their equality tests, return true

alert(undefined == null); / / return true

#### Please describe the event bubbling

Event bubbling: When an event is triggered on an element, such as a mouse click on a button, the same event will be triggered on all of that element’s ancestors. This process is called event bubbling; This event bubbles from the original element all the way to the top of the DOM tree.

#### Scope and variable declaration enhancement in JavaScript?

There are only two types of scope in Js (before CS6) : global scope and function scope. Globally-scoped variables and functions can be called from anywhere. Variables and functions in a function scope can only be used inside a function.

Local variables are always defined throughout the function body, and we can move the variable declaration “ahead” to the top of the function body while the variable initialization remains where it was.

var scope="global";  
function t(){  
  console.log(scope);  //undefined
	var scope="local"  
	console.log(scope);  
}  
t(); 
Copy the code

Variable promotion in the global scope,

Global variables declared using the var keyword also elevate the declaration of the variable to the header

console.log(scope);//undefined
var scope="global";  
Copy the code

Target vs. currentTarget

  • Target is the actual element that the event fires

  • CurrentTarget is the element of the event binding

  • The this pointer in the event handler is currentTarget

  • CurrentTarget and Target, sometimes the same element, sometimes not (because the event bubbles)

    • When the event is triggered by a child element, currentTarget is the element of the binding event and target is the child element
    • CurrentTarget and Target are the same element when the event is triggered by the element itself.

Target: the source component that triggers the event (the component to which the event is registered/bound)

CurrentTarget: The current event triggered by the event (the current event can be the source component that triggered the event, or the triggered event component (the child element of the triggered event source component).

JS macro task and micro task difference and usage

Macro tasks are generally: including the overall code script, setTimeout, setInterval, I/O, UI render. Microtasks include Promise, Object.observe, and MutationObserver.

vue.js

#### Vue instance lifecycle

Main classification of life cycle functions:

Life cycle functions during creation:

BeforeCreate: The instance has just been created in memory and the data and methods properties have not been initialized

Created: The instance has created OK in memory, data and methods have created OK, and template compilation has not started

BeforeMount: At this point the template is compiled but not mounted to the page

Mounted: A compiled template is mounted to a specified container

Runtime lifecycle functions:

BeforeUpdate: This function is executed before the status update, when the status value in data is the latest, but the data displayed on the interface is old because the DOM nodes have not yet been re-rendered

Updated: This function is called when the instance is updated. The state values in data and the displayed data are updated and the interface is rerendered.

Life cycle functions during destruction:

BeforeDestroy: Called before instance destruction. At this step, the instance is still fully available.

Destroyed: Called after the Vue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed.

! [image-20190930090231773](file:///Users/jing/Library/Application Support/typora-user-images/image-20190930090231773.png? lastModify=1614516486)

####Vue rendering process analysis

Vue recommends using templates to create your HTML in most cases. But a template is a template, not a real DOM node. There are a few steps to go from the template to the actual DOM node

  1. Compile the template into the render function
  2. Instance mount, according to the root node render function call, recursive generation of virtual DOM
  3. Compare the virtual DOM and render to the real DOM
  4. When the data inside the component changes, the component and its child components invoke the Render function again using data as props to generate the virtual DOM, and return to Step 3

Output Hello World using vue

<! DOCTYPEhtml>
<html lang="en">
<head>
    <title>Document</title>
</head>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<body>
    <div id="app">
        <p>{{ msg }}</p>
    </div>
    <! Use MSG to render the page.

    <script>
        Create an instance of vue
        var vm = new Vue({
            el: '#app'.data: {
                msg: 'Hello world!!! '}})</script>
</body>
</html>
Copy the code

Why does data have to be a function in a VUE component

First, Vue will report an error directly if it is not a function. Second, the reason is that Vue makes each component object return a new object, because if it is of the same object, components will interact with each other after multiple uses.

Difference between Watch and computed in VUE

  1. computedThe result of an attribute is cached, except for the recalculation of dependent, reactive attribute changes, which are used as attributes. Computed allows you to listen to values in the V-Model (data) and recalculate them whenever they change. Computed must have a return value;
  2. methodsMethod represents a specific operation, mainly writing business logic;
  3. watchAn object whose key is the expression to observe and whose value is the corresponding callback function. It is mainly used to monitor the changes of some specific data, so as to carry out some specific business logic operations. In addition to monitoring changes in data values, watch can monitor changes in routes. Two parameters in Watch are the new value and the old value. Can be seen ascomputedandmethodsCombination of;

What are the common modifiers in VUE

V-model decorator Lazy decorator: By default, v-model synchronizes input box data in input events by default. In other words, the data in the corresponding data will be automatically changed once the data is changed. Lazy modifiers cause data to be updated only when it is out of focus or when it is hit: Number modifiers: By default, letters and numbers are treated as strings in the input field. But if we want to deal with numeric types, it's better to treat the content as a number. The number modifier automatically converts input to a numeric type: trim modifier: If the input has a lot of whitespace at the beginning and end, we usually want to remove the trim modifier by filtering the whitespace on both sides of the content. The V-on modifier. Stop - calls event.stopPropagation(). .prevent - Call event.preventdefault (). . {keyCode | keyAlias} - only events from the specific trigger callback key trigger. .native - Listens for the native event of the component root element. .once - Only one callback is triggered.Copy the code

! [image-20210228172050050](/Users/jing/Library/Application Support/typora-user-images/image-20210228172050050.png)

What are the communication modes between Vue components?

Collate 8 general communication schemes in VUE

  1. Pass through props

  2. Emit a custom event through $emit

  3. Use the ref

  4. EventBus

  5. $parent or $root

  6. Vuex

  7. Attrs and listeners

  8. Dojo.provide and Inject

V – model principle

V-model is a syntax sugar that essentially consists of two operations: 1. V-bind binds a value attribute, and 2. V-on binds the input event to the current element

V – the router routing

$router = VueRouter; $router = VueRouter; $route = VueRouter; $router = VueRouter

What is a navigation guard (global guard)? Vue-router provides a navigational guard that listens for incoming and outgoing routes. Vue-router provides beforeEach and afterEach hook functions that fire before and after a route is about to change.

The three parameters of the navigation hook are parsed: to: route object to the destination to be entered from: current navigation route object to be left Next: call this method before entering the next hook

If it is a post-hook, that is, afterEach, you do not actively call the next() function

Route exclusive guard

Define beforeEnter directly on route configuration

Guards within components

The following route navigators are directly defined within the routing component:

  • beforeRouteEnter

  • BeforeRouteUpdate (2.2 New)

  • beforeRouteLeave

####keep-alive

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering. They have two very important properties: include-string or regular expression. Only matching components are cached; exclude-string or regular expression, and any matching components are not cached

Vuex

Vuex is a state management mode developed specifically for vue.js applications. Simply think of it as storing all the variables that need to be shared by multiple components in one object. This object is then placed in the top-level Vue instance for other components to use.)

ES6

ForEach, map, some, filter, findIndex

These are all new methods of arrays, and they’re going to iterate over each item in the array and do something about it;

forEach()

ForEach has no return value.

Is a normal for loop. It is simpler to write than a for loop and applies to normal loops.

Takes three arguments: the element of each array, index, and itself.

let a1 = ['hello'.'world']
  let b1 = a1.forEach((item, i, arr) = > {
      console.log(item, i, arr)
  })
console.log(b1) // undefined
Copy the code

map()

Map returns a new array.

It is recommended to use Map instead of forEach when returning a new array

let a2 = [1.2.3]
let b2 = a2.map(v= > {
    return v * 2
})
console.log(a2) / / [1, 2, 3]
console.log(b2) / / (2, 4, 6]
Copy the code

filter()

Filter returns a new array.

Returns an array that matches the specified criteria

let a3 = [
        {
            title: 'heading 1'.show: true
        },
        {
            title:'title 2'.show: false
        },
        {
            title:'title'.show: true}]let b3 = a3.filter(item= > {
        return item.show // return data where show is true
    })
    console.log(b3) / / [{title: "heading 1", show: true}, {title: "title", show: true}]

Copy the code

some()

Some returns Boolean data.

Returns true if one of the elements in the array meets the specified requirements, false otherwise

let a4 = ['yellow', 'red', 'blue']
let b4 = a4.some(v => {
  return v === 'red'
})
console.log(b4) // true
Copy the code

every()

Every returns Boolean data.

Return true if all elements in the array meet the specified requirements, false otherwise

let a5 = [2.4.6.8]
let b5 = a5.every(v= > {
  return v % 2= = =0 // Check whether the elements in the array are all even numbers
})
console.log(b5) // true
Copy the code

reduce()

Reduce can be used to compute the sum of arrays

let a6 = [1.2.3.4.5.6 ,7.8.9.10]
/** * preTotal: sum of previous values * currentValue: currentValue */
let b6 = a6.reduce((preTotal, currentValue) = > {
  console.log(currentValue) / * 1, 2... 7, 8, 9 * /
  return preTotal + currentValue
})
console.log(b6) / / 55
Copy the code

find()

Find returns the value of the first element of the array that passes the specified condition.

let a8 = [
  {
    name: 'Tom'.age: 18
  },
  {
    name: 'Anny'.age: 15
  },
  {
    name: 'Kobe'.age: 22},]let b8 = a8.find((item) = > {
  return item.age > 15
})
console.log(b8) // {name: 'Tom', age: 18}
Copy the code

let/var

1. In fact, the design of var can be regarded as a design error of JavaScript language. About 10 years ago, Brendan Eich decided to fix this problem by adding a new keyword: let. We can think of let as a more perfect VAR

When var is used to declare a variable in JS, the scope of the variable is mainly related to the definition of the function. There is no scope for other block definitions, such as if/for, which often causes problems in our development.

What is the difference between creating variables using let, var, and const?

// Let is a block-level scope. If we use let inside a function, we have no effect on the outside of the function. If we do not initialize the output, we will report syntax errors
let c = 3;
console.log('Let defines c:' + c);/ / output c = 3
function change(){
	let c = 6;
	console.log(Let defines c: + c);/ / output c = 6
} 
change();
console.log('Let definition c after function call is not affected by function internal definition:' + c);/ / output c = 3

// Const is a global scope. A variable declared by const cannot be modified directly and must be initialized. Const is usually used in defining and modifying arrays
 
	const b = 2;/ / right
	// const b; // Error, must be initialized
	console.log('Const definition b:' + b);// There is output value
	// b = 5;
	// console.log(' change const definition b: '+ b); // Cannot output
 
// var Global variable. The declared variable can be modified. If the output is not initialized, undefined will be reported, but no error will be reported
 
var a = 1;
// var a; // No error will be reported
console.log(Var defines a: + a);// a=1
function change(){
	a = 4;
	console.log(Var defines a: + a);// a=4
} 
change();
console.log(Var defines a as the internal value of the function: + a);// a=4
Copy the code

The use of the const

The const keyword already exists in many languages, such as C/C++, to modify a variable to a constant. In JavaScript, too, identifiers decorated with const are constants and cannot be reassigned. When do you use const? We can use const to keep the data safe when the identifier we decorate will not be reassigned. Tip: In ES6 development, use const in preference and let only when you need to change an identifier.

 // 1. Note one: Once an identifier decorated with const has been assigned, it cannot be modified
  // const name1 = 'why';
  // name1 = 'abc';

  // 2. Note 2: To define an identifier using const, an assignment must be made
  // const name;

  // 3. Note 3: Constant means that the object cannot be modified, but the internal properties of the object can be changed.
  const obj = {
    name: 'why'.age: 18.height: 1.88
  }
  // obj = {}
  console.log(obj);

  obj.name = 'kobe';
  obj.age = 40;
  obj.height = 1.87;

  console.log(obj);
Copy the code

4. Object literals are enhanced

// 1. Attribute enhancement
  const name = 'why';
  const age = 18;
  const height = 1.88
  // ES5
  const obj11 = {
    name: name,
    age: age,
    height: height
  }
  const obj = {
    name,
    age,
    height,
  }
  console.log(obj);
	
	// 2
  // ES5
  const obj = {
    run: function () {},eat: function () {}}const obj = {
    run(){},eat(){}}Copy the code