The most comprehensive front-end interview summary interviews high-frequency interview questions summarized by N companies. classic! Must pass the exam!

Table of contents

1. Array processing reduce() method

(1) Find the sum of all values ​​in the array

(2) Convert a two-dimensional array to a one-dimensional array

(3) Calculate the number of occurrences of each element in the number.

 (4) Array deduplication

2. ES6 map() method

(1) Use map to calculate arbitrarily complex functions

(2) Use Map to format array objects

 3. Es6 syntax to deduplicate arrays (2 ways)

(1) Use ES6 to deduplicate the simplest common array [...new Set(arr)]

(2) Use the reduce() method to deduplicate. (see above for example)

4. What is the difference between computed calculation and watch?

(1) The difference between the two

(2) Usage scenarios

5. What is the difference between created and mounted in Vue?

6. DOM event model

(1) Event bubbling

(2) Event capture

(3) Dom event flow

(1) html event handler

(2) DOM0 level event handler

(3) DOM2 level event handler

7. Slot, named slot

8. How does vue father and son, brothers, grandparents and grandchildren communicate (important)

1 Parent-child component communication

(1) Parent components pass values ​​to child components

(2) The child component modifies the properties of the parent component and calls the method of the parent component

(3) The parent component calls the child component method

2. Sibling component communication

3. Communication between grandparents and grandchildren

9. Why is data in vue a function?

10. How to handle routing jump to 404

11. The difference between slice() and splice()

12. The method of judging whether it is an array (4 methods)

13. The difference between for in and for of

14. The difference between $router and $route in vue

15. The difference between this.$route.params and this.$route.query

16. The difference between the map method and forEach

forEach

17. Prototypes and prototype chains

prototype chain

18 Differences between @import and link introduction styles

1. Differences in affiliation

2. The difference in loading order

3. Compatibility difference


1. Array processing reduce() method

reduce()The method sequentially executes a reducer function  provided by you for each element in the array   . Each run of  the reducer  will pass in the calculation results of the previous elements as parameters, and finally summarize the results into a single return value.

The reducer  iterates through the array elements one by one, and each step adds the value of the current element to the result of the previous step (the result of the previous step is the sum of all elements before the current element) - until no more elements are added

(1) Find the sum of all values ​​in the array

let sum = [0, 1, 2, 3].reduce(function (a, b) {
  return a + b
}, 0)

或者用箭头函数
let sum=[1,2,3,4].reduce((a,b)=>a+b,0)

The initial value is set, and the result is 20

[1, 2, 3, 4].reduce( 
(previousValue, currentValue, currentIndex, array) 
=> previousValue + currentValue,10 )

(2) Convert a two-dimensional array to a one-dimensional array

let arr = [[0, 1], [2, 3], [4, 5]].reduce(
  function(a, b) {
    return a.concat(b)
  },
  []
)

(3) Calculate the number of occurrences of each element in the number.

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']

let newName = names.reduce(function (a, b) {
  if (b in a) {
    a[b]++
  }
  else {
    a[b] = 1
  }
  return a
}, {})
// newName is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

 (4) Array deduplication

let arr = ['a', 'b', 'a', 'b', 'c']
let newArr = arr.reduce(function (a, b) {
  if (a.indexOf(b) === -1) {
    a.push(b)
  }
  return a
}, [])

console.log(newArr)


2. ES6 map() method

map() method creates a new array consisting of the values ​​returned by calling the provided function once for each element in the original array. 

// 箭头函数
map((element) => { /* … */ })
map((element, index) => { /* … */ })
map((element, index, array) => { /* … */ })

// 回调函数
map(callbackFn)
map(callbackFn, thisArg)

// 内联回调函数
map(function(element) { /* … */ })
map(function(element, index) { /* … */ })
map(function(element, index, array){ /* … */ })
map(function(element, index, array) { /* … */ }, thisArg)

The function will be called once for each element in the original array in order  callback . The return values ​​(including undefinedcallback )  after each execution  are combined to form a new array

(1) Use map to calculate arbitrarily complex functions

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

(2) Use Map to format array objects

var kvArray = [{key: 1, value: 10},
               {key: 2, value: 20},
               {key: 3, value: 30}];

var reformattedArray = kvArray.map(function(obj) {
   console.log(obj);
   var rObj = {};
   rObj[obj.key] = obj.value;
   return rObj;
});
console.log(reformattedArray);


 3. Es6 syntax to deduplicate arrays (2 ways)

(1) Use ES6 to deduplicate the simplest common array [...new Set(arr)]

// 原始数组
var arr = [1,2,3,2,2,4,5,6];
// 使用解构方式 去重的核心方法
var newArr = [...new Set(arr)];
// 去重后数据
console.log(newArr);

(2) Use the reduce() method to deduplicate. (see above for example)

indexOf()Method returns the first index in the array at which a given element can be found, or -1 if it does not exist


4. What is the difference between computed calculation and watch?

(1) The difference between the two

computed computed attribute, calculated by attribute

The result of the property will be cached and recalculated unless the dependent reactive property changes. When the dependent responsive property has not changed, the result of calling the current function will be read from the cache. Return must be used to return the result.

The watch attribute monitors and monitors changes in attributes . Mainly monitor data changes, and then execute related business logic.

(2) Usage scenarios

computed when a property is affected by multiple properties.

                   Scenario: Checkout of shopping cart items

watch When one piece of data affects multiple pieces of data

                    Scenario: Search Data


5. What is the difference between created and mounted in Vue?

created: called before the template is rendered into html
mounted: called after the template is rendered into html, after the page is initialized, operate on the dom node

6. DOM event model

An event is an action performed by the user or the browser, such as a click event. DOM supports a large number of events, and the interaction between JS and HTML is realized through events.

Event Flow: Describes the firing sequence of events .

(1) Event bubbling

Event bubbling is IE's event flow. The most specific element accepts the event and propagates up step by step until it reaches the Document object. Google Chrome will be passed to the window object.

Prevent event bubbling
e.stopPropagation() can interrupt bubbling. Capture cannot be canceled.

(2) Event capture

From non-specific nodes to specific nodes, it is generally propagated from the document object, which is the opposite of event bubbling. rarely use.

(3) Dom event flow

There are 3 phases: event capture phase, target phase, and event bubbling phase.

Event handler: A function that responds to an event.

(1) html event handler

HTML's on attribute. The monitoring code specified by this method will only be triggered during the bubbling phase.

<button onclick="doSomething()">点击</button>

(2) DOM0 level event handler

In fact, it is the event attribute of the element node.

var btn = document.getElementById('btn');
btn.onclick = function () {
  console.log('被点击了!');
};

Get the reference of the button, and assign it the event onclick, and output 'clicked!' on the console after clicking! '.
If you want to remove the event handler, just do thisbtn.onclick = null; // 删除事件处理程序

(3) DOM2 level event handler

addEventListener() and removeEventListener() , for adding and removing event handlers.

target.addEventListener(eventType, listener[, useCapture]);

eventType — event name, case sensitive
listener — listener function
useCapture — optional parameter, default false, which means the listener function is only triggered in the bubbling phase. true to execute the function in the capture direction

function print() {
  console.log('Print Hello world');
}

var btn = document.getElementById('btn');
btn.addEventListener('click', print, false);

The meaning of the above code is that the element whose node id is btn uses the addEventListener method to bind the click event, and when clicked, the listening function print will occur. Also, since useCapture is set to false, this function is only triggered during the bubbling phase.
 

7. Slot, named slot

The popular understanding of slot Slot is "occupation of the pit". It occupies a position in the component template. When the component tag is used, the content in the component tag will automatically fill in the pit (replacing the position in the component template slot)

Sometimes we need multiple slots for a component, at this time we can use named slots.

For example, for a component with the following template  <base-layout> :

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

An export without   will have the implicit name "default" name . <slot>

<template> We can use  v-slot a directive on an element and  v-slot provide its name as an argument when providing content to a named slot  :

<base-layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

Any way of writing will render: ( note that  v-slot it can only be added on  <template> top)

<div class="container">
  <header>
    <h1>Here might be a page title</h1>
  </header>
  <main>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </main>
  <footer>
    <p>Here's some contact info</p>
  </footer>
</div>

8. How does vue father and son, brothers, grandparents and grandchildren communicate (important)

1 Parent-child component communication

(1) Parent components pass values ​​to child components

        The parent component uses the sub-component tag to internally configure the v:bind instruction to pass attributes, that is: title="title" :obj="obj" and so on, and the sub-component receives the parent component by configuring props:{} properties of

(2) The child component modifies the properties of the parent component and calls the method of the parent component

       The child component configures $emit to pass value, and the parent component configures v-on to receive

(3) The parent component calls the child component method

       Bind ref to the subcomponent to call the method of the subcomponent through this.$ref

2. Sibling component communication

  1. Two child components communicate through the parent component
  2. vuex
  3. Global event bus $eventBus

3. Communication between grandparents and grandchildren

  1. Global event bus $eventBus
  2. vuex
  3. use attr /attr/listener

9. Why is data in vue a function?

1.  Prevent data reuse;

2.  Guarantee data independence ; data data in vue components should be isolated from each other and not affect each other

3.  Scope ; every time a component is reused, a new piece of data is returned, with its own scope, allowing each component instance to maintain its own data.

In summary, if data is a function, a new data will be returned every time the component is reused.

If objects are used, the data used on each instance (component) affects each other

10. How to handle routing jump to 404

Two common methods for jumping to the specified 404 page if the vue route does not match the route

(1) Implemented through vue-router redirection

When we cannot continue to visit due to various reasons such as entering a wrong URL address, then we can use the redirection method, as long as the code is added to the route.

let router = new VueRouter({
    routes:[
       {path:'/',redirect:{name:"home"}},  // 重定向到主页
       {name:'home',path:'/home',component:Home},
       {path:'/music',component:Music},
       {path:'/movie',component:Movie},
       {name:'img',path:'/picture22',component:Picture},
       {name:'musicDetail',path:'/musicDetail/:id/:name',component:MusicDetail},
       {path:'*',component:NotFound},//全不匹配的情况下,返回404,路由按顺序从上到下,依次匹配。最后一个*能匹配全部,
    ]
});

(2) Routing global guard

router.beforeEach((to, from, next) => {
  if (to.matched.length ===0) {  //如果未匹配到路由
    from.name ? next({ name:from.name }) : next('/');   //如果上级也未匹配到路由则跳转登录页面,如果上级能匹配到则转上级路由
  } else {
    next();    //如果匹配到正确跳转
  }
});

11. The difference between slice() and splice()

slice() method returns a new array object that is a  shallow copy  of the original array determined by begin and  (inclusive  , exclusive ). The original array will not be changed .endbeginend

slice() // do not intercept
slice(start) //start is positive from start to end. start is negative, starting from the penultimate number
slice(start, end) //include start, not end.

example

1. slice(2). //return array from index 2 to end

2. slice(2,4) //returns an array from index 2 to index 3

3. slice(-2). //Return the last 2 slices

4. slice(2,-1). //From index 2 to the penultimate value.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]


console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

splice() The method modifies the array by deleting or replacing existing elements or adding new elements in place , and returns the modified content as an array. This method mutates the original array.

splice(start)                                            //Delete all elements from the index start
splice(start, deleteCount)                  //start starts from the index, deleteCount indicates the number of array elements to be removed
splice(start, deleteCount, item1)          // Item1, item2 to be added to the array element
splice(start, deleteCount, item1, item2, itemN)

Example:

1. splice(2, 0, "drum"); //Delete 0 elements from index 2 and insert into drum. 

2.splice(3, 1) // Delete 1 element from index 3

3.splice(-2, 1) // Delete 1 element from index -2

4.splice(2); // Delete all elements from index 2

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

12. The method of judging whether it is an array (4 methods)

(1) instanceof judgment.

const a = [];
const b = {};
console.log(a instanceof Array);//true
console.log(a instanceof Object);//true, the Object constructor can also be found on the prototype chain of the array

It is to judge whether an Object is an array (in JavaScript, an array is actually an object),

If the Array constructor can be found on the prototype chain of this Object, then this Object should be an array. If only the Object constructor can be found on the prototype chain of this Object, then it is not an array.

(2) Use the isArray method of the Array object to judge

const a = [];
const b = {};
Array.isArray(a);//true
Array.isArray(b);//false

(3) Judging by the constructor

const a = [];
console.log(a.constructor == Array);//true

The constructor attribute can be rewritten. After the constructor attribute is modified, this method cannot be used to determine whether the array is an array

(4) Use Object's toString method to judge

Object.prototype.toString.call(['Hello','Howard'])    //"[object Array]"

You can write a method to determine whether an array is an array:

const isArray = (something)=>{
    return Object.prototype.toString.call(something) === '[object Array]';
}

cosnt a = [];
const b = {};
isArray(a);//true
isArray(b);//false

Note ⚠️: typeof cannot determine whether it is an array. typeof will judge null, objects and arrays as objects.

const a = null;
const b = {};
const c= [];
console.log(typeof(a)); //Object
console.log(typeof(b)); //Object
console.log(typeof(c)); //Object

13. The difference between for in and for of

for of and  for inare properties used to traverse

the difference

  1. for in  properties for iterating over arrays or objects
  2. for of Can only be used for arrays , not objects,
  3. for in get object keyor array index
  4. for ofAnd forEachthe same, is to get the value directly
   const arr = ['a', 'b', 'c']
   // for in 循环
   for (let i in arr) {
       console.log(i)         //输出  0  1  2
   }
   
   // for of
   for (let i of arr) {
       console.log(i)         //输出  a   b   c
   }

   const obj = {
        a: 1,
        b: 2,
        c: 3
    }
    for (let i in obj) {
        console.log(i)    //输出 : a   b  c
    }
    for (let i of obj) {
        console.log(i)    //输出: Uncaught TypeError: obj is not iterable 报错了
    }

 

forEach is specially used to loop the array , you can get the element directly, and you can also get the index value


let arr = ['a', 'b', 'c', 'd']
    arr.forEach( (val, index)=> {
    console.log('index:'+index+','+'val:'+val) // val是当前元素,index当前元素索引,arr数组
})

14. The difference between $router and $route in vue

(1) By  this.$router accessing the router, it is equivalent to obtaining the entire routing file. The global router instance contains many methods and instances. this.$router.push, same as router-link jump

(2)  Obtain information related to this.$route the current route by accessing the current route

15. The difference between this.$route.params and this.$route.query

1. The same points can be used to pass parameters and get parameters

eg:传参
    this.$router.push({
        path: '/monitor',
        query: {
            id: id,
         }
    }
    this.$router.push({
        path: '/monitor',
        params: {
            id: id,
         }
    }

取参
    this.$route.query.id
    this.$route.params.id

2. Differences

Use query to pass parameters to display parameters in url , refresh route jump page parameters do not disappear
use params to pass parameters in url do not display parameters , refresh route jump page parameters disappear

eg:
  query:  http://172.19.186.224:8080/#/monitor?id=1
  params: http://172.19.186.224:8080/#/monitor

16. The difference between the map method and forEach

The same point: map & forEach are used to traverse the array more conveniently .

Difference : map does not change the original array and returns a new array.

forEach mutates the original array and has no return value, i.e. it returns undefined.

forEach

// 箭头函数
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// 回调函数
forEach(callbackFn)
forEach(callbackFn, thisArg)



callbackFn.     // 为数组中每个元素执行的函数。

函数调用时带有以下参数:

element.        // 数组中正在处理的当前元素。

index.          //数组中正在处理的当前元素的索引。

array.          //forEach() 方法正在操作的数组。

thisArg 可选.    //可选参数。当执行回调函数 callbackFn 时,用作 this 的值。

The forEach method is used to call each element of the array and pass the element to the callback function.

const items = ['item1', 'item2', 'item3'];
const copyItems = [];

items.forEach((item) => {
  copyItems.push(item);
});

17. Prototypes and prototype chains

5 prototypical rules are the basis for learning the prototypical chain   

(1) All reference types (arrays, objects, functions) have object characteristics, that is, properties can be freely extended (except null)

(2) All reference types (arrays, objects, functions) have a _proto_ attribute (implicit prototype) , and the attribute value is an ordinary object. 

(3)  All functions have a prototype attribute (explicit prototype) , and the attribute value is also an ordinary object.

(4)  All reference types (arrays, objects, functions) _proto_ attribute (implicit prototype) value points to the "prototype" attribute value (explicit prototype) of its constructor.

         var obj={};    obj._proto_ === Object.prototype

  (5) When trying to get a property of an object, if the object itself does not have this property, it will go to its _proto_ (that is, the prototype of its constructor) to find it.

prototype chain

In order to avoid an infinite loop, JS sets the __proto__ of Object.prototype to null, so if it has not been found here, it will return null.

18 Differences between @import and link introduction styles

1. Differences in affiliation

@importIt is a grammatical rule provided by CSS, and it only has the function of importing style sheets;

linkIt is a tag provided by HTML, which can not only load CSS files, but also define RSS, rel connection attributes, etc.

2. The difference in loading order

When the page is loaded, linkthe CSS introduced by the tag is loaded at the same time;

@importImported CSS will be loaded after the page has loaded.

3. Compatibility difference

@importIt is a syntax unique to CSS2.1, so it can only be recognized by IE5+;

linkTags are HTML elements, so there are no compatibility issues.

Guess you like

Origin blog.csdn.net/weixin_39089928/article/details/124967170