19
头图

Preface

Hello, everyone, I’m Lin Sanxin. is the prerequisite for advanced . I will share with you today. I have encountered 50 "basic knowledge points" in my work this year. I have recorded knowledge points this year. Haha. Those with full marks can find me to get gifts!

50 basic knowledge points

1. How many data types does JavaScript have?

  • number: number type
  • string: string type
  • boolean: Boolean value type
  • undefined: undefined type
  • null: null value type
  • object: object type
  • symbol: symbol type
  • bigint: big number type

2. What is the largest safe number and smallest safe number of JavaScript?

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 copy layer by layer, shallow copy only copies the first layer, deep copy is just a reference
  • In a deep copy, the changes in the new object will not affect the original object, while in a shallow copy, the changes in the new object will also be changed in the original object.
  • In a deep copy, the original object does not share the same properties with the new object, while in a shallow copy, they have the same properties.

4. What is a closure?

Closure is a function that can read the internal variables of other functions

  • Advantages: enable external access to local things
  • Disadvantages: Improper use can easily cause memory leaks
    example:

    function a () {
    let num = 0
    
    // 这是个闭包
    return function () {
       return ++num
    }
    }
    const b = a()
    console.log(b()) // 1
    console.log(b()) // 2

5. What is the prototype chain? More details!

Check out my article: Nuggets talk about "prototype chain", the best and most easy-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 不会报错

Function promotion

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

if (false) {
  function fun2(){}
}
console.log(fun2) // undefined 不会报错

Function promotion priority> Variable promotion priority

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

7. The difference between isNaN and Number.isNaN?

  • isNaN: In addition to judging NaN as true, it also judges the ones that cannot be converted into numbers as true, such as'xxx'
  • Number.isNaN: It is true only when NaN is judged, and it is false in other cases

8. When solving the problem of traversing objects, what should I do if the properties on the prototype are traversed?

Use hasOwnProperty 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
// 使用 hasOwnProperty
for (const key in person) {
  person.hasOwnProperty(key) && console.log(key)
} // name

9, valueOf and toString

  • 1. valueOf prefers calculation, toString prefers display
  • 2. When the object is converted, call toString
  • 3. First call toString for forced number valueOf
  • 4. Under normal circumstances, call toString
  • 5. In the case of arithmetic operators, call valueOf

Call valueOf

Callerreturn valueReturn value type
ArrayThe array itselfArray
BooleanBoolean valueBoolean
DateMillisecondsNumber
FunctionFunction itselfFunction
NumberNumeric valueNumber
ObjectObject itselfObject
StringStringString

Call toString

Callerreturn valueReturn value type
ArrayArray to string, equivalent to Array.join()String
BooleanConvert 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
StringStringString

10. What is the specific storage format of JavaScript variables in memory?

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

11. Tell me about the boxing and unboxing of JavaScript?

Boxing: the operation of converting basic data types into corresponding reference data types

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 turned out to be a boxing operation inside JavaScript

  • 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

    Unboxing: the operation of converting the reference data type into the corresponding basic data type

    Unboxing operation is realized through valueOf or toString

    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 all empty variables
  • All are false values, and all Boolean values are false
  • null == undefined is true
    difference
  • typeof judges null as object, judges undefined as undefined
  • Null turns to number as 0, undefined turns to number as NaN
  • Null is an object is not initialized, undefined is initialized, but the assignment is undefined
  • 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): can judge most types
  • Array.isArray(xxx): Determine whether it is an array

14. Why is typeof null an object?

Different data types are expressed in binary at the bottom. The first three bits of the binary are 000 will be judged to object type 061a2dff1e8988, and the binary at the bottom of null is all 0, so the first three 000 must also be 061a2dff1e8989, so it is judged to be object

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

  • ==: There will be implicit conversions during the comparison
  • ===: It needs the same type and the same value to be true

16. What are the implicit conversion rules of JavaScript?

  • 1. Convert to string type: + (string concatenation)
  • 2. Converted to number type: ++/-- (increment and decrement operator) +-* /% (arithmetic operator)> <>= <= == != === !=== (relational operation symbol)
  • 3. Converted to boolean type:! (Logical not operator)

17. What are the conversion rules for the left and right sides of the double equal sign?

  • 1. null == undefined is true
  • 1. If one of the operands is a Boolean value, convert it to a value before comparing for equality-false is converted to 0, and true is converted to 1;
  • 2. If one operand is a string and the other operand 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 use the obtained basic type value to compare according to the previous rules

18. Why is undefined >= undefined false?

According to the implicit conversion rule of , it can be converted to NaN >= NaN , NaN is not equal to NaN, nor greater than, so it is false

19. Why is null >= null true?

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

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

According to the conversion rules on the left and right sides of

  • . 1, ! higher priority than == , [] not false, it first converted into [] == false
  • 2. The right side is a boolean value, false first turns the number 0 , so it can be converted to [] == 0
  • 3. The object on the left, [] calls toString to '' , and then to '' == 0
  • 4. The left side is a string, '' converted to 0 , and the final is 0 == 0

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

No, there is a loss of precision in JavaScript calculations

console.log(0.1 + 0.2 === 0.3) // false
  • Reason: The decimals in JavaScript are floating-point numbers and need to be converted to binary for calculation. Some decimals cannot be expressed in binary, so they can only be approximated, which causes errors.
  • Solution:

    • First becomes an integer operation, and then back to a decimal
    • toFixed() performance is not good, 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);

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

23. How many ways are there to bind click events?

Three kinds

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

24. What is the third parameter of addEventListence?

The third variable passes a boolean value, need to prevent bubbling, the default is false, do not prevent bubbling

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

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

    console.log(fun) // fun () {}
    // 函数表达式
    var fun = function(name) {}
    // 函数声明
    function fun () {}
    console.log(fun) // fun (name) {}

26. What are the JavaScript event flow models?

  • 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 an encapsulation of the XMLHttpRequest object (XHR)
  • Axios: It is a encapsulation of XHR objects based on Promise
  • Fetch: It is a method of window, also based on Promise, but has nothing to do with XHR and does not support IE

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

The steps to load the DOM document are:

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

29. How to stop the incident from bubbling up?

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. This is the event delegation. The advantages are:

  • Binding to the parent element only needs to be bound once, saving performance
  • The child elements do not need to bind the same event to each
  • If a new child element is added later, it will automatically receive the event listener of the parent element due to the event delegation.

32. How to achieve array deduplication?

// 使用 Map 去重
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
}

// 使用 Set 去重
function quchong (arr) {
    return [...new Set(arr)]
}

33. What is the difference between Set and Array?

It is recommended to read the article of Teacher Ruan Yifeng: Set and Map data structure

34. What is the difference between Map and Object?

It is recommended to read the article of teacher Ruan Yifeng: Set and Map data structure

35. What is NaN? What are the characteristics?

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

36. What are the methods to deal with asynchronous?

  • Callback
  • promise
  • Event monitoring
  • Publish and subscribe
  • async await

    37. How many methods are there for JavaScript inheritance?

    Pre-work

    // 定义一个动物类
    function Animal (name) {
    // 属性
    this.name = name || 'Animal';
    // 实例方法
    this.sleep = function(){
      console.log(this.name + '正在睡觉!');
    }
    }
    // 原型方法
    Animal.prototype.eat = function(food) {
    console.log(this.name + '正在吃:' + food);
    };

    1. Prototype chain inheritance

    Core: Take the instance of the parent class as the prototype of the subclass

    function Cat(){ 
    }
    Cat.prototype = new Animal();
    Cat.prototype.name = 'cat';
    
    var cat = new Cat();
    console.log(cat.name); // cat
    cat.eat('fish') // cat正在吃:fish
    cat.sleep() // cat正在睡觉!
    console.log(cat instanceof Animal); //true 
    console.log(cat instanceof Cat); //true

    advantage:

  • 1. Very pure inheritance relationship, the instance is the instance of the subclass, and also the instance of the parent class
  • 2. The new prototype method/attribute of the parent class can be accessed by the subclass
  • 3. Simple and easy to implement
    shortcoming:
  • 1. If you want to add new attributes and methods to the new Animal() , you must execute it after a statement like 061a2dff1e94a1, and you can't put it in the constructor
  • 2. All properties from the prototype object are shared by all instances
  • 3. When creating a child instance, you cannot pass parameters to the parent class constructor
  • 4. Multiple inheritance is not supported

2. Structural inheritance

Core: Using the constructor of the parent class to enhance the instance of the subclass is equivalent to copying the instance properties of the parent class to the subclass (the prototype is not used)

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

var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom正在睡觉!
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true

advantage:

  • 1. Solved the problem that in prototype chain inheritance, the subclass instance shared the parent class reference attribute
  • 2. When creating a subclass instance, you can pass parameters to the parent class
  • 3. Multiple inheritance can be achieved (call multiple parent objects)
    shortcoming:
  • 1. The instance is not the instance of the parent class, the instance of the knowledge subclass
  • 2. It can inherit the instance properties and methods of the parent class, but not the prototype properties/methods
  • 3. Function reuse cannot be achieved. Each subclass has a copy of the instance function of the parent class, which affects performance

3. Instance inheritance

Core: Add new features to the parent class instance and return it as a child class instance

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正在睡觉!
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 new subclass () or subclass (), the returned object has the same effect
    shortcoming:
  • 1. An instance is an instance of a parent class, not an instance of a subclass
  • 2. Multiple inheritance is not supported

4. Copy inheritance

Core: Just copy one by one

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正在睡觉!
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true

advantage:

  • 1. Support multiple inheritance
    shortcoming:
  • 1. Low efficiency and high memory usage (because of copying the attributes of the parent class)
  • 2. Unable to obtain the non-enumerable method of the parent class (non-enumerable method, cannot be accessed by for in)

5. Combination inheritance

Core: Through the construction of the parent class, inherit the properties of the parent class and retain the points of passing parameters, and then realize the function reuse by using the parent class instance as the subclass 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正在睡觉!
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true

advantage:

  • 1. To make up for structural inheritance, you can inherit instance attributes/methods, and can also inherit prototype attributes/methods
  • 2. It is both an instance of a subclass and an instance of the parent class
  • 3. There is no problem of reference attribute sharing
  • 4. Passable parameters
  • 5. Functions can be reused
    shortcoming:
  • 1. The parent class constructor is called twice, and two instances are generated (the subclass instance shields the copy on the subclass prototype)

6. Parasitic combination inheritance

Core: Cut off the instance attributes of the parent class through parasitism, so that when the construction of the parent class is called twice, the instance method/attribute will not be initialized twice, avoiding the shortcomings of inheritance combination

function Cat(name) {
  Animal.call(this);
  this.name = name || 'Tom';
}
// 创建一个没有实例方法的类
var Super = function () { };
Super.prototype = Animal.prototype;
//将实例作为子类的原型
Cat.prototype = new Super();

// Test Code
var cat = new Cat();
console.log(cat.name); // Tom
cat.sleep() // Tom正在睡觉!
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true

advantage:

  • 1. It's perfect
    shortcoming:
  • 1. Complex implementation

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 pattern 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 pointed to by this?

  • 1. The new operator creates an instance

    function Person(name) {
    this.name = name
    console.log(this)
    }
    // this指向当前person实例对象
    const person = new Person('Sunshine_Lin')
  • 2. Point to window

    function fn() {
    console.log(this)
    }
    fn() // 浏览器window,node里global
  • 3. Object calling method

    const target = {
    fn: function () { console.log(this) }
    }
    target.fn() // target
    
    // 这种就是改变了this了
    const fn = target.fn
    fn() // 浏览器window,node里global
  • 4. Call, apply, bind to change this

    const obj1 = {
    name: '林三心',
    sayName: function() {
      console.log(this.name)
    }
    }
    const obj2 = {
    name: 'Sunshin_Lin'
    }
    // 改变sayName的this指向obj2
    obj1.sayName.call(obj2) // Sunshin_Lin
    // 改变sayName的this指向obj2
    obj1.sayName.apply(obj2) // Sunshin_Lin
    // 改变sayName的this指向obj2
    const fn = obj1.sayName.bind(obj2)
    fn() // Sunshin_Lin

40. What are the common methods of arrays?

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
shiftDelete the first item of the array and return the array
unshiftAdd an element at the beginning of the array and return the added element
reserveReverse an array and return the modified array
sortSort an array and return the modified array
spliceIntercept the array and return the intercepted interval
joinConcatenate all elements of an array into a string and return this string
concatarr1.concat(arr2, arr3) concatenate array
joinarr.join(x) joins the arr array elements into a string and returns this string
mapOperate each item in the array and return a new array
forEachTraverse the array, no return value
filterJudge all items in the array and return a new array that meets the rules
everyEach item in the array meets the rules before returning true
someReturn true if there is an item in the array that meets the rules
reduceReceive the previous return and the next item in the array
flatArray flattening
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 smallest value in arr
Math.ceil (decimal)Decimals are rounded up
Math.floor (decimal)Decimals are rounded down
Math.round (decimal)Round off decimals
Math.sqrt(num)Square num
Math.pow(num, m)Raise num to the power of m
Math.random() * numTake a random number from 0-num

42. What factors cause memory leaks? How to solve?

Please see my article Which is the great god? Just use other people’s Tanabata date to organize "JS to avoid memory leaks"

43. Talk about JavaScript's garbage collection mechanism

Read my article: give you 13 pictures to help you beat 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, namely:

  • Alert
  • Confirm
  • Prompt

    45. How to convert JS date to ISO standard

toISOString() The method is used to convert js dates to ISO standards. It uses the ISO standard to convert the js Date object into a string. like:

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

46. How to encode and decode URLs in JS

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

Note that : encodeURI() will not encode characters like this: /?: @ & = + $ #, if you need to encode these characters, please use encodeURIComponent(). usage:

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

decodeURI() The 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 browser object model , browser object model

apieffectRepresentative method or attribute
window.historyManipulate the browser's recordshistory.back()
history.go(-1)
window.innerHeightGet the height of the browser window
window.innerWidthGet the width of the browser window
window.locationOperation refresh button and address barlocation.host: get the domain name and port
location.hostname: get the host name
location.port: get the port number
location.pathname: get the path of the url
location.search: get the beginning part
location.href: get the whole url
location.hash: Get the part starting with #
location.origin: Get the current domain name
location.navigator: Get the current browser information

48. The relationship between BOM and DOM

BOM The Browser Object Model, that is, the browser object model, which mainly deals with browser windows and frames.

The full name of DOM is Document Object Model, which is an application program interface (API) of HTML and XML, which follows W3C standards, and is a standard that all browsers comply with.

JS accesses, controls, and modifies the client (browser) by accessing the BOM BOM contains the document, the properties and methods of the window object are directly usable and aware. , So you can directly use the document property of the window object, and you can access, retrieve, and modify the content and structure of the XHTML document through the document property. Because the document object is the root node of the DOM.

It can be said that the BOM contains the DOM (object). The browser provides access to the BOM object. From the BOM object, the DOM object can be accessed, so that js can operate the browser and the document read by the browser.

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

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

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

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

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

50. Explain "use strict"?

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

Concluding remarks

If you think this article is of little help to you, please give me a thumbs up and encourage Lin Sanxin haha. Or you can join my fish-fishing group. Let's study hard together, ah, ah, ah, ah, I will mock interviews regularly, resume guidance, answer questions and answer questions, let's learn from each other and make progress together! !
截屏2021-11-28 上午9.43.19.png


Sunshine_Lin
2.1k 声望7.1k 粉丝