For the 50 basic knowledge points of JavaScript encountered at work, give me a full score and get a prize

preface

Hello, I'm Lin Sanxin. Foundation is the premise of advanced. Today, I'll share with you the 50 "basic knowledge points" I have encountered in my work in the past year. I have the habit of recording knowledge points in the past year. Ha ha. Full marks can ask me for gifts!

50 basic knowledge points

1. How many data types does JavaScript have?

  • Number: number type
  • String: string type
  • boolean: boolean type
  • undefined: type is not defined
  • Null: null value type
  • Object: object type
  • Symbol: symbol type
  • bigint: large number type

2. JavaScript maximum security number and minimum security number?

console.log(Number.MAX_SAFE_INTEGER)
// 9007199254740991

console.log(Number.MIN_SAFE_INTEGER)
// -9007199254740991

3. What is the difference between deep copy and shallow copy?

  • Deep copy copies layer by layer, shallow copy only copies the first layer, and deep copy is only a reference
  • In a deep copy, changes in the new object do not affect the original object, while in a shallow copy, changes in the new object are changed in the original object.
  • In a deep copy, the original object does not share the same properties as the new object, but in a shallow copy, they have the same properties.

4. What is a closure?

A closure is a function that can read internal variables of other functions

  • Advantages: external access to local things
  • Disadvantages: improper use is easy to cause memory leakage
    example:

    function a () {
    let num = 0
    
    // This is a closure
    return function () {
       return ++num
    }
    }
    const b = a()
    console.log(b()) // 1
    console.log(b()) // 2

5. What is the prototype chain? Be more detailed!

Look at my article: Nuggets talk about "prototype chain", which is the best and easiest to understand

6. What is variable promotion? Function promotion?

Variable promotion

console.log(name) // undefined
var name = 'Sunshine_Lin'

if (false) {
  var age = 23
}
console.log(age) // undefined will not report an error

Function promotion

console.log(fun) // function fun() {}
function fun() {}

if (false) {
  function fun2(){}
}
console.log(fun2) // undefined will not report an error

Function raise priority > variable raise priority

console.log(fun) // function fun() {}
var fun = 'Sunshie_Lin'
function fun() {}
console.log(fun) // 'Sunshie_Lin'

7. What is the difference between isNaN and Number.isNaN?

  • isNaN: in addition to judging that NaN is true, it also judges that it cannot be converted into a number as true, such as' xxx '
  • Number.isNaN: true only when judging NaN, and false in other cases

8. When solving the traversal object, what should I do if I traverse the properties on the prototype?

Use hasOwnProperty to judge

function Person(name) {
  this.name = name
}
Person.prototype.age = 23
const person = new Person('Sunshine_lin')
for (const key in person) { console.log(key) } // name age
// Use hasOwnProperty
for (const key in person) {
  person.hasOwnProperty(key) && console.log(key)
} // name

9. valueOf and toString

  • 1. valueOf is biased towards operation and toString is biased towards display
  • 2. During object conversion, toString is called first
  • 3. Strong conversion of string takes precedence over toString, and strong conversion of number takes precedence over valueOf
  • 4. Normally, toString is called first
  • 5. valueOf is called first in case of operation operator

Call valueOf

caller Return valuereturn type
ArrayArray itselfArray
BooleanBoolean valueBoolean
DateMsec Number
FunctionFunction itselfFunction
NumberNumeric valueNumber
ObjectObject itselfObject
Stringcharacter stringString

Call toString

caller Return valuereturn type
ArrayArray to string, equivalent to Array.join()String
BooleanTo string 'true', 'false'String
DateString date, such as' Fri Dec 23 2016 11:24:47 GMT+0800 (China standard time) 'String
NumberNumeric stringString
Object'[object Object]'String
Stringcharacter stringString

10. How are JavaScript variables stored in memory?

  • Basic data type: stored in stack memory
  • Reference data type: the pointer is stored in stack memory, pointing to an address in heap memory, and the content is stored in heap memory
  • There is also a saying that all JavaScript data is stored in heap memory. I also agree with this statement

11. Talk about JavaScript packing and unpacking?

Boxing: the operation of converting a basic data type to a corresponding reference data type

Look at the following code. s1 is just a basic data type. How can it call indexOf?

const s1 = 'Sunshine_Lin'
const index = s1.indexOf('_')
console.log(index) // 8

It turns out that the JavaScript performs the boxing operation internally

  • 1. Create an instance of String type;
  • 2. Call the specified method on the instance;
  • 3. Destroy this instance;

    var temp = new String('Sunshine_Lin')
    const index = temp.indexOf('_')
    temp = null
    console.log(index) // 8

    Unpacking: the operation of converting the reference data type to the corresponding basic data type

    Unpacking is realized through valueOf or toString methods

    var objNum = new Number(123);  
    var objStr =new String("123");   
    console.log( typeof objNum ); //object
    console.log( typeof objStr ); //object 
    console.log( typeof objNum.valueOf() ); //number
    console.log( typeof objStr.valueOf() ); //string
    
    console.log( typeof objNum.toString() ); // string 
    console.log( typeof objStr.toString() ); // string

12. What are the similarities and differences between null and undefined?

Same point

  • Are null variables
  • All values are false, and all Boolean values are false
  • null == undefined is true
    difference
  • typeof determines that null is object and undefined is undefined
  • null to 0, undefined to NaN
  • null means an object is uninitialized, undefined means it is initialized but has no assignment defined
  • null === undefined is false

13. How to judge the data type?

  • typeof xxx: can judge number, string, undefined, boolean, object, function (null is object)
  • Object.prototype.toString.call(xxx): it can judge most types
  • Array.isArray(xxx): judge whether it is an array

14. Why is typeof null an object?

Different data types are represented by binary at the bottom. If the first three bits of binary are 000, it will be judged as object type, while if the binary at the bottom of null is all 0, the first three bits must be 000, so it will be judged as object

15. What is the difference between = = and = =?

  • ==: there will be implicit conversions during the comparison
  • ===: you need the same type and value to be true

16. Implicit conversion rules for JavaScript?

  • 1. Convert to string type: + (string connector)
  • 2. Convert to number type: + + / - - (self increasing and self decreasing operator) + - * /% (arithmetic operator) > < > = < = = =! = = ======== (relational operator)
  • 3. Convert to boolean type:! (logical non operator)

17. The conversion rules on the left and right sides of the double equal sign?

  • 1. null == undefined is true
  • 1. If one of the operands is Boolean, convert it to a numeric value before comparing equality - false to 0 and true to 1;
  • 2. If one operand is a string and the other is a numeric value, convert the string to a numeric value before comparing equality
  • 3. If one operand is an object and the other operand is not, call the toString() method of the object and compare the obtained basic type value according to the previous rules

18. Undefined > = why is undefined false?

According to the implicit conversion rules, it can be converted to NaN > = NaN. NaN is neither equal to nor greater than NaN, so it is false

19. Null > = why is null true?

According to the implicit conversion rules, it can be converted to 0 > = 0, 0 equals 0, so it is true

20. [] = =! [] Why is it true?

Follow the conversion rules on the left and right sides of the double equal sign

  • 1. ! priority is higher than = =, [] is not false, so it is converted to [] = = false first
  • 2. The Boolean value is on the right, and false first turns to the number 0, so it can be converted to [] = = 0
  • 3. On the left is the object, [] calls toString to '', which is converted to '' = = 0
  • 4. On the left is the string, '' converted to 0, and finally 0 = = 0

21. 0.1 + 0.2 = = = 0.3, right?

No, there is a loss of precision in JavaScript calculation

console.log(0.1 + 0.2 === 0.3) // false
  • Reason: in JavaScript, decimals are floating-point numbers and need to be converted to binary for operation. Some decimals cannot be expressed in binary, so they can only take approximate values, resulting in errors
  • resolvent:

    • First it becomes an integer operation, and then it becomes a decimal
    • toFixed() has poor performance and is not recommended

22. What is an anonymous function?

Anonymous function: a function without a function name, such as:

(function(x, y){
    alert(x + y);  
})(2, 3);

Here, an anonymous function is created (in the first bracket), and the second bracket is used to call the anonymous function and pass in parameters.

23. How to bind click events?

Three kinds

  • xxx.onclick = function (){}
  • <xxx onclick=""></xxx>
  • xxx.addEventListence('click', function(){}, false)

24. What is the third parameter of addeventlisting?

The third variable passes a Boolean value. Do you need to prevent bubbling? The default is false. Bubbling is not prevented

25. What is the difference between function declaration and function expression?

  • Function declaration: enjoy function promotion
  • Function expression: classified as variable declaration, enjoy variable promotion
  • Function raise priority > variable raise priority

    console.log(fun) // fun () {}
    // Function expression
    var fun = function(name) {}
    // Function declaration
    function fun () {}
    console.log(fun) // fun (name) {}

26. What are the event flow models of JavaScript?

  • Event bubbling: received by the most specific element and propagated upward
  • Event capture: received by the least specific element and propagated down
  • DOM event flow: event capture - > target stage - > event bubbling

27. What is the difference between Ajax, Axios and Fetch?

  • Ajax: is the encapsulation of XMLHttpRequest object (XHR)
  • Axios: encapsulates XHR objects based on Promise
  • Fetch: it is a window method and Promise based, but it has nothing to do with XHR and does not support IE

28. What is the difference between load, $(document).ready and DOMContentLoaded?

The steps for loading DOM documents are as follows:

  • 1. Parse HTML structure.
  • 2. Load external scripts and style sheet files.
  • 3. Parse and execute the script code.
  • 4. DOM tree construction is complete// DOMContentLoaded triggered, $(document).ready triggered
  • 5. Load external files such as pictures.
  • 6. Page loading completed// load trigger

29. How to prevent event bubbling?

function stopBubble(e) {
  if (e.stopPropagation) {
    e.stopPropagation()
  } else {
    window.event.cancelBubble = true;
  }
}

30. How to prevent the default behavior of events?

function stopDefault(e) {
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    window.event.returnValue = false;
  }
}

31. What is event delegation?

When all child elements need to bind the same event, you can bind the event to the parent element, which is event delegation. The advantages are as follows:

  • Binding on the parent element only needs to be bound once to save performance
  • Child elements do not need each to bind to the same event
  • If a new child element is added later, the event listener of the parent element will be automatically received due to event delegation

32. How to realize array de duplication?

// Use Map to remove duplicate
function quchong1(arr) {
  const newArr = []
  arr.reduce((pre, next) => {
    if (!pre.get(next)) {
      pre.set(next, 1)
      newArr.push(next)
    }
    return pre
  }, new Map())
  return newArr
}

// Use Set to remove duplicate
function quchong (arr) {
    return [...new Set(arr)]
}

33. What is the difference between Set and Array?

It is suggested to read teacher Ruan Yifeng's article: Set and Map data structures

34. What is the difference between Map and Object?

It is suggested to read teacher Ruan Yifeng's article: Set and Map data structures

35. What is NaN? What are the characteristics?

  • NaN is not equal to itself, that is, NaN === NaN is false
  • NaN is false, and the Boolean value is false
  • NaN is essentially a number, typeof NaN === number

36. What are the methods to deal with asynchrony?

  • Callback function
  • promise
  • event listeners
  • Publish and subscribe
  • async await

    37. How many JavaScript inheritance methods are there?

    Front work

    // Define an animal class
    function Animal (name) {
    // attribute
    this.name = name || 'Animal';
    // Example method
    this.sleep = function(){
      console.log(this.name + 'be sleeping!');
    }
    }
    // Prototype method
    Animal.prototype.eat = function(food) {
    console.log(this.name + 'I am eating:' + food);
    };

    1. Prototype chain inheritance

    Core: take the instance of the parent class as the prototype of the child class

    function Cat(){ 
    }
    Cat.prototype = new Animal();
    Cat.prototype.name = 'cat';
    
    var cat = new Cat();
    console.log(cat.name); // cat
    cat.eat('fish') // cat is eating: fish
    cat.sleep() // cat is sleeping!
    console.log(cat instanceof Animal); //true 
    console.log(cat instanceof Cat); //true

    advantage:

  • 1. A very pure inheritance relationship. An instance is an instance of a child class and an instance of a parent class
  • 2. Prototype methods / properties are added to the parent class, which can be accessed by all subclasses
  • 3. Simple and easy to implement
    Disadvantages:
  • 1. To add properties and methods to subclasses, you must execute them after statements such as new Animal(), and cannot put them in the constructor
  • 2. All properties from the prototype object are shared by all instances
  • 3. Cannot pass arguments to the parent constructor when creating a child instance
  • 4. Multiple inheritance is not supported

2. Construction inheritance

Core: using the constructor of the parent class to strengthen the instance of the child class is equivalent to copying the instance attribute of the parent class to the child class (no prototype is used)

function Cat(name) {
  Animal.call(this);
  this.name = name || 'Tom';
}

var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom is sleeping!
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true

advantage:

  • 1. It solves the problem that subclass instances share parent class reference properties in prototype chain inheritance
  • 2. When you create a subclass instance, you can pass parameters to the parent class
  • 3. Multiple inheritance can be implemented (call multiple parent objects)
    Disadvantages:
  • 1. An instance is not an instance of a parent class, but an instance of a knowledge subclass
  • 2. It is an instance property and method that can inherit the parent class, but cannot inherit the prototype property / method
  • 3. Function reuse cannot be realized. Each subclass has a copy of the parent class instance function, which affects performance

3. Instance inheritance

Core: add new features for parent class instances and return them as child class instances

function Cat(name){
  var instance = new Animal();
  instance.name = name || 'Tom';
  return instance;
}

var cat = new Cat();
console.log(cat.name) // Tom
cat.sleep() // Tom is sleeping!
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // false

advantage:

  • 1. There is no restriction on the calling method. Whether it is a new subclass () or a subclass (), the returned object has the same effect
    Disadvantages:
  • 1. An instance is an instance of a parent class, not a child class
  • 2. Multiple inheritance is not supported

4. Copy inheritance

Core: copy by copy

function Cat(name){
  var animal = new Animal();
  for(var p in animal){
    Cat.prototype[p] = animal[p];
  }
  this.name = name || 'Tom';
}

var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom is sleeping!
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true

advantage:

  • 1. Support multiple inheritance
    Disadvantages:
  • 1. Low efficiency and high memory consumption (because the properties of the parent class need to be copied)
  • 2. Cannot get parent class enumerable method (enumerable method, cannot be accessed using for in)

5. Combinatorial inheritance

Core: inherit the attributes of the parent class through the parent class construction and retain the point of passing parameters, and then realize function reuse by taking the parent class instance as the child class prototype

function Cat(name){
  Animal.call(this);
  this.name = name || 'Tom';
}
Cat.prototype = new Animal();

Cat.prototype.constructor = Cat;

var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom is sleeping!
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true

advantage:

  • 1. It can inherit instance properties / methods or prototype properties / methods
  • 2. It is both an instance of a child class and an instance of a parent class
  • 3. There is no reference property sharing problem
  • 4. Transmittable parameter
  • 5. Function reusability
    Disadvantages:
  • 1. The parent class constructor is called twice and two instances are generated (the subclass instance masks the one on the subclass prototype)

6. Parasitic combinatorial inheritance

Core: cut off the instance attribute of the parent class through parasitic method, so that the instance method / attribute will not be initialized twice when calling the construction of the parent class twice, so as to avoid the disadvantage of inheritance combination

function Cat(name) {
  Animal.call(this);
  this.name = name || 'Tom';
}
// Create a class without an instance method
var Super = function () { };
Super.prototype = Animal.prototype;
//Prototype instances as subclasses
Cat.prototype = new Super();

// Test Code
var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom is sleeping!
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true

advantage:

  • 1. Perfect
    Disadvantages:
  • 1. Implementation complexity

38. What are the ways to create an object?

new Object creation

const obj = new Object()
obj.name = 'Sunshine_Lin'

Literal creation

const obj = { name: 'Sunshin_Lin' }

Factory mode creation

function createObj(name) {
  const obj = new Object()
  obj.name = name
  return obj
}
const obj = createObj('Sunshine_Lin')

Constructor creation

function Person(name) {
  this.name = name
}
const person = new Person('Sunshine_Lin')

39. Four situations where this points?

  • 1. The new operator creates an instance

    function Person(name) {
    this.name = name
    console.log(this)
    }
    // this points to the current person instance object
    const person = new Person('Sunshine_Lin')
  • 2. Point to window

    function fn() {
    console.log(this)
    }
    fn() // global in browser window and node
  • 3. Object call method

    const target = {
    fn: function () { console.log(this) }
    }
    target.fn() // target
    
    // This is what changed this
    const fn = target.fn
    fn() // global in browser window and node
  • 4. call, apply, bind change this

    const obj1 = {
    name: 'Lin Sanxin',
    sayName: function() {
      console.log(this.name)
    }
    }
    const obj2 = {
    name: 'Sunshin_Lin'
    }
    // Change this of sayName to obj2
    obj1.sayName.call(obj2) // Sunshin_Lin
    // Change this of sayName to obj2
    obj1.sayName.apply(obj2) // Sunshin_Lin
    // Change this of sayName to obj2
    const fn = obj1.sayName.bind(obj2)
    fn() // Sunshin_Lin

40. What are the common methods of array?

methodeffectWhether to affect the original array
pushAdd an element after the array and return the length of the array
popDelete the last item of the array and return the deleted item
shiftDeletes the first item of the array and returns the array
unshiftAdd an element at the beginning of the array and return the added element
reserveInvert an array and return the modified array
sortSort an array and return the modified array
spliceIntercept the array and return the intercepted interval
joinConcatenates all elements of an array into a string and returns the string
concatarr1.concat(arr2, arr3) join array
joinarr.join(x) concatenates the arr array elements into a string and returns the string
mapOperates on each item of the array and returns a new array
forEachTraversal array, no return value
filterJudge all items of the array and return a new array that meets the rules
everyThe array returns true only when each item meets the rule
someIf the array has one item that meets the rule, it returns true
reduceReceive the previous return and the next item of the array
flatFlatten arrays
sliceIntercept the array and return the intercepted interval

41. What are the common methods of Math?

methodeffect
Math.max(arr)Take the maximum value in arr
Math.min(arr)Take the minimum value in arr
Math.ceil (decimal)Decimal rounded up
Math.floor (decimal)Decimal down rounding
Math.round (decimal)Decimal rounding
Math.sqrt(num)Square num
Math.pow(num, m)Take the m-power of num
Math.random() * numTake the random number of 0-num

42. What factors lead to memory leakage? How to solve it?

Please read my article Which is the great God? Just use other people's Tanabata dating time to sort out "JS to avoid memory leakage"

43. Talk about JavaScript garbage collection mechanism

Look at my article: Give you 13 pictures to help you defeat the "V8 garbage collection mechanism" in 20 minutes

44. What are the different types of pop-up boxes in JS?

There are three types of pop-up boxes available in JS:

  • Alert
  • Confirm
  • Prompt

    45. How to convert JS date to ISO standard

toISOString()   Method is used to convert js dates to ISO standards. It uses the ISO standard to convert js Date objects to strings. For example:

var date = new Date();
var n = date.toISOString();
console.log(n);
// YYYY-MM-DDTHH:mm:ss.sssZ

46. How to encode and decode URL s in JS

encodeURI()   The function is used to encode the URL in JS. It takes the URL string as a parameter and returns an encoded string.

be careful:   encodeURI() does not encode characters like this:  / ? : @ & = + $ #, If you need to encode these characters, use encodeURIComponent(). Usage:

var uri = "my profile.php?name=sammer&occupation=pāntiNG";
var encoded_uri = encodeURI(uri);

decodeURI()   Function is used to decode the URL in js. It takes the encoded URL string as a parameter and returns the decoded string. Usage:

var uri = "my profile.php?name=sammer&occupation=pāntiNG";
var encoded_uri = encodeURI(uri);
decodeURI(encoded_uri);

47. What is BOM? What are the APIs?

BOM is the browser object model

apieffectRepresents a method or property
window.historyRecord of manipulating browserhistory.back()
history.go(-1)
window.innerHeightGets the height of the browser window
window.innerWidthGets the width of the browser window
window.locationAction refresh button and address barlocation.host: get the domain name and port
location.hostname: get the hostname
location.port: get port number
location.pathname: get the path of the url
location.search: get? Beginning part
location.href: get the entire url
location.hash: get # start part
location.origin: get the current domain name
location.navigator: get the current browser information

48. Relationship between BOM and DOM

The full name of BOM is Browser Object Model, that is, Browser Object Model, which mainly deals with browser windows and frames.

The full name of DOM is Document Object Model, that is, Document Object Model. It is the application program interface (API) of HTML and XML, which follows the W3C standard and the public standard of all browsers.

JS accesses, controls and modifies the client (browser) by accessing the BOM (Browser Object Model) object. Since the window of the BOM contains document, the attributes and methods of the window object can be directly used and perceived, so you can directly use the document attribute of the window object, and you can access, retrieve Modify the content and structure of XHTML documents. Because the document object is the root node of the DOM.

It can be said that the BOM contains DOM (object). The access provided by the browser is the BOM object. From the BOM object to the DOM object, js you can operate the browser and the documents read by the browser.

49. What is the difference between substr() and substring() functions in JS

substr()   The form of the function is substr(startIndex,length). It returns a substring from startIndex and a number of 'length' characters.

var s = "hello";
( s.substr(1,4) == "ello" ) // true

substring()   The form of the function is substring(startIndex,endIndex). It returns a substring from startIndex to endIndex - 1.

var s = "hello";
( s.substring(1,4) == "ell" ) // true

50. Explain "use strict"?

"Use strict" is a js instruction introduced in Es5. The purpose of using the "use strict" instruction is to enforce code in strict mode. In strict mode, we cannot use variables without declaring them. Earlier versions of js ignored "use strict".

epilogue

If you think this article is of little help to you, give a praise and encourage Lin Sanxin, ha ha. Or you can join my fishing group
If you want to enter the learning group and fish group, please check my home page and add me, and note: if you think no, I will broadcast the simulated interview regularly to answer questions and solve doubts

Full marks, hurry to find me!!! Or tell me in the comment area~~~

Tags: Javascript Front-end ECMAScript Interview

Posted on Mon, 01 Nov 2021 19:25:21 -0400 by ShibSta