A directory

No toss of the front end, and salted fish what’s the difference

directory
A directory
The preface
Three COMMON DOM apis
Difference between null and undefined
Five flow of events
 5.1 the addEventListener
 5.2 the principle
 5.3 case
 5.4 exercises
 5.5 Preventing Bubbles
 5.6 Differences between onMouseOver and onMouseEnter
 5.7 science
The difference between typeof and instanceof
Describe this in seven sentences
Eight JS position
Nine JS drag and drop
SetTimeout implements setInterval
Xi Realize Sleep
Xii Execution context
 12.1 Execution context type
 12.2 execution stack
Functional programming
 13.1 Features of functional programming
 13.2 pure functions
Progressive Web Applications (PWA)
 14.1 the advantages
 14.2 disadvantages
Xv Standardization
 15.1 CommonJS specification
 15.2 AMD specification
 15.3 CMD specification
 15.4 ES6 Modules specifications
How Babel is compiled
Seventeen problem set
 17.1 Common apis for Arrays
 17.2 Common DOM apis
 17.3 De-Duplicating arrays
 17.4 Digital amount
 17.5 Traversal Problem
 17.6 setTimeout
 17.7 requestAnimationFrame
 17.8 Temporary dead zone
 17.9 Output The Printed Result
 17.10 Output The Printed Result
 17.11 the Event Loop
 17.12 Producing the Printed Result
 17.13 Make a == 1 && a == 2
18 More

The preface

Returns the directory

During the JavaScript review process, you might encounter:

  1. nullundefinedThe difference between?
  2. addEventListenerFunction?

Or a == 1 && a == 2.

Categorize them under JavaScript Basics and cover them in this article.

At the same time, there will be a dozen simple questions practice.

Three COMMON DOM apis

Returns the directory

You can use the DOCUMENT or Window element’s API to manipulate the document itself or to get subclasses of the document (the various elements in the Web page).

// Get the element
const node = document.getElementById(id); / / or querySelector (". The class | | # id name ");

// Create the element
const heading = document.createElement(name); // name: p, div, h1...
heading.innerHTML = ' ';

// Add the element
document.body.appendChild(heading);

// Delete the element
document.body.removeChild(node);
Copy the code

Example:

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>DOM manipulation</title>
  <style>
    div {
      border: 1px solid #ccc;
      padding: 50px;
      width: 100px;
    }
  </style>
</head>
<body>
  <div id="dom1">Element 1</div>
  <div class="dom2">Element 2</div>
  
  <button class="btn">Am I</button>

  <script>
    (function() {
      const btn = document.querySelector('.btn');

      // Register the click event
      btn.onclick = function() {
        const dom1 = document.getElementById('dom1');

        // The first way to add elements
        const newDom1 = document.createElement('p');
        newDom1.innerHTML = '< a href = "https://github.com/LiangJunrong/document-library" > jsliang document library < / a >';
        dom1.appendChild(newDom1);

        // The second element to add
        const newDom2 = document.createElement('ul');
        newDom2.innerHTML = ` 
  • aaa
  • bbb
  • `
    ; document.body.appendChild(newDom2); // Remove the element const dom2 = document.querySelector('.dom2'); document.body.removeChild(dom2); } })()
    </script> </body> </html> Copy the code

    Difference between null and undefined

    Returns the directory

    The application scenarios are as follows:

    • null:
    1. Number(null)get0.
    2. As an argument to a function, indicating that the argument to the function is not an object.
    3. As the end point of the object prototype chain.Object.prototype.__proto__ === null.
    • undefined:
    1. Number(undefined)getNaN.
    2. The variable declared but not assigned is equal toundefined.
    3. When calling a function, the corresponding argument is not provided, and so onundefined.
    4. Object is not assigned. The value of this property isundefined.
    5. The function does not return a value; it returns by defaultundefined.

    Five flow of events

    Returns the directory

    What is an event flow: An event flow describes the order in which events are received from the page. The DOM level 2 event flow consists of the following stages.

    • Event capture phase
    • In the target stage
    • Event bubble phase

    How to let events bubble and then capture:

    In the DOM standard event model, it’s capture before bubble. However, if you want to achieve the effect of bubble first and then capture, for the same event, monitor capture and bubble, respectively corresponding to the corresponding handler function, listen to the capture event, first delay execution, until the bubble event is captured and then execute the capture.

    5.1 the addEventListener

    Returns the directory

    The addEventListener method registers the specified listener with the EventTarget, and when the object fires the specified event, the specified callback function is executed.

    The addEventListener event target can be the elements on the Document, Element, Document, and Window, or any other object that supports events (such as XMLHttpRequest).

    Reference documents: [EventTarget addEventListener – MDN] [developer.mozilla.org/zh-CN/docs/…].

    • Grammar:target.addEventListener(type, listener, options/useCapture)
    1. type: a string representing the type of the listener event
    2. listener: receives an event notification object.
    3. options: is related to a specifiedlistenerProperty. Optional values arecapture(Event capture phase propagates here to trigger),once(in thelistenerValue is called at most once after adding),passive(set totruesaidlistenerNever callpreventDefault()).
    4. useCapture: In the DOM tree, registeredlistenerShould precede the element below itEventTargetCall thelistener.

    The third argument to addEventListener involves bubble and capture, which is true for capture and false for bubble.

    Or an object {passive: true} for Safari, used when scrolling is disabled/enabled

    • The sample
    <! DOCTYPEhtml>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>The listener</title>
    </head>
    <body>
      <table id="outside">
        <tr><td id="t1">one</td></tr>
        <tr><td id="t2">two</td></tr>
      </table>
    
      <script>
        (function() {
          // Add the function
          const modifyText = (text) = > {
            const t2 = document.querySelector('#t2');
            if (t2.firstChild.nodeValue === text) {
              t2.firstChild.nodeValue = 'two';
            } else{ t2.firstChild.nodeValue = text; }}// Add event listener to Table
          const element = document.querySelector('#outside');
          element.addEventListener('click'.function() { modifyText('four')},false); }) ()</script>
    </body>
    </html>
    Copy the code

    As shown above, this example simply achieves the effect of clicking two to switch to four, and clicking four to switch back to two.

    5.2 the principle

    Returns the directory

    Event capture and event bubble are Netscape’s and IE’s descriptions of the DOM event generation sequence, respectively.

    Netscape believes that DOM should first receive events from window, then document, and then layer by layer, and finally receive events from specific elements, that is, event capture.

    IE believes that DOM events should be received by specific elements first, and then layer by layer, then document, and finally window, which is event bubble.

    Finally, W3C unified the two schemes: DOM event is divided into two stages, event capture and event bubble stage.

    When an element is clicked, there is the event capture phase. The window receives the event first, then captures the event layer by layer, and finally receives the event by the specific element. After that, the concrete elements are bubbled up layer by layer to receive events from the window.

    So:

    • The event bubblingWhen an event is bound to a target element, the event in turn is triggered on its parent element (if the parent element also has an event of the same name, e.g. if the child element and the parent are bound)clickEvent to trigger the parent elementclick).
    • Event capture: As opposed to bubbling, it is passed from the top to the bottom.

    5.3 case

    Returns the directory

    Here’s an example with a custom event:

    <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" The content = "width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no" > < meta HTTP - equiv = "X-ray UA - Compatible" <title> </head> <body> <ul class="ul"> <li class="li"> <button class=" BTN "> </li> </ul> <script> window.onload = function() { const myEvent = document.createEvent('CustomEvent'); myEvent.initEvent('myEvent', true, true); const btn = document.querySelector('.btn'); btn.addEventListener('myEvent', function(e) { console.log('button'); }) const li = document.querySelector('.li'); li.addEventListener('myEvent', (e) => { console.log('li'); }) const ul = document.querySelector('.ul'); li.addEventListener('myEvent', (e) => { console.log('ul'); }) document.addEventListener('myEvent', (e) => { console.log('document'); }) window.addEventListener('myEvent', (e) => { console.log('window'); }) setTimeout(() => { btn.dispatchEvent(myEvent); }, 2000); }; </script> </body> </html>Copy the code

    Button -> li -> ul -> document -> window

    In the case of capture, the opposite is true.

    5.4 exercises

    Returns the directory

    Click on an input event that triggers in turn

    const text = document.getElementById('text');
    
    text.onclick = function (e) {
      console.log('onclick')
    }
    text.onfocus = function (e) {
      console.log('onfocus')
    }
    text.onmousedown = function (e) {
      console.log('onmousedown')
    }
    text.onmouseenter = function (e) {
      console.log('onmouseenter')}Copy the code

    The correct order is: onMouseEnter -> onMouseDown -> onFocus -> onClick.

    If you add onmouseup, it’s:

    • onmouseenter -> onmousedown -> onfocus -> onmouseup -> onclick

    5.5 Preventing Bubbles

    Returns the directory

    • event.stopPropagation();
    btn.addEventListener('myEvent'.function(e) {
      console.log('button');
      event.stopPropagation();
    })
    Copy the code

    By preventing the bubble, the program will only print the button instead of continuing to print li and so on.

    5.6 Differences between onMouseOver and onMouseEnter

    Returns the directory

    Both of these fire when you move in, but onMouseover fires multiple times, and onMouseEnter only fires when you enter.

    5.7 science

    Returns the directory

    Not all events have bubbles, for example:

    • onblur
    • onfocus
    • onmouseenter
    • onmouseleave

    The difference between typeof and instanceof

    Returns the directory

    • typeof: detection of a variable type except the basic typenullExcept for functions, reference types are normally displayed asfunction, and the others are displayed asobject.
    • instanceofIt is mainly used to detect whether the prototype object of a constructor is in the prototype chain of an object.

    Typeof NULL is a historical Bug. Typeof NULL outputs object because earlier versions of JavaScript were 32-bit systems that used to store variable type information in low order for performance reasons. Null means all zeros, so it misreads object.

    In addition to the Object. The prototype. ToString. Call judge variables for ().

    Details visible: JavaScript – variables

    Describe this in seven sentences

    Returns the directory

    For functions, the object that points to the last call to the function is an internal object automatically generated when the function is running and can only be used inside the function. Globally, this points to window.

    Eight JS position

    Returns the directory

    • clientHeight: indicates the height of the visible areaborderAnd the scroll bar
    • offsetHeight: represents the height of the visible area, includingborderAnd the scroll bar
    • scrollHeight: represents the height of all areas, including those that are hidden by scrolling
    • clientTop: Indicates borderborderThe thickness of, if not specified, is generally0
    • scrollTop: The height to be hidden after scrolling, which gets the object relative to the height byoffsetParentProperty (the CSS locates the element orbodyThe element is the height from the top.

    Nine JS drag and drop

    Returns the directory

    1. throughmousedown,mousemove,mouseupMethod implementation
    2. By HTML 5DragDropimplementation

    SetTimeout implements setInterval

    Returns the directory

    This is an alternative knowledge point, was going to classify handwritten source series, but think too low, no card face, into the basic series:

    const say = () = > {
      // do something
      setTimeout(say, 200);
    };
    
    setTimeout(say, 200);
    Copy the code

    Clear this timer:

    let i = 0;
    
    const timeList = [];
    
    const say = () = > {
      // do something
      console.log(i++);
      timeList.push(setTimeout(say, 200));
    };
    
    setTimeout(say, 200);
    
    setTimeout(() = > {
      for (let i = 0; i < timeList.length; i++) {
        clearTimeout(timeList[i]); }},1000);
    Copy the code

    Xi Realize Sleep

    Returns the directory

    As follows, implement the other content after 1000 milliseconds:

    const sleep = time= > {
      return new Promise((resolve, reject) = > {
        setTimeout(() = > {
          resolve(time);
        }, time);
      });
    };
    
    sleep(1000).then((res) = > {
      console.log(res);
    });
    Copy the code

    Xii Execution context

    Returns the directory

    12.1 Execution context type

    Returns the directory

    There are three types of execution context in JavaScript:

    • Global execution context: This is the default or underlying context. Any code that is not inside a function is in the global context. It does two things: create a globalwindowObject (in the case of the browser) and SettingsthisIs equal to the global object. There is only one global execution context in a program.
    • Function execution context: Each time a function is called, a new context is created for that function. Each function has its own execution context, which is created when the function is called. There can be any number of function contexts. Each time a new execution context is created, it performs a series of steps in the order defined.
    • The Eval function executes context: perform inevalThe code inside the function also has its own execution context, which is not often used by JavaScript developersevalSo I won’t discuss it here.

    12.2 execution stack

    Returns the directory

    An execution stack, or “call stack” as it is known in other programming languages, is a stack that has a LIFO (last in, first out) data structure that is used to store all the execution contexts created while the code is running.

    When the JavaScript engine first encounters your script, it creates a global execution context and pushes it onto the current execution stack. Whenever the engine encounters a function call, it creates a new execution context for that function and pushes it to the top of the stack.

    The engine executes functions whose execution context is at the top of the stack. When the function finishes execution, the execution context pops off the stack and the control flow goes to the next context in the current stack.

    let a = 'Hello World! ';
    
    function first() {
      console.log('Inside first function');
      second();
      console.log('Again inside first function');
    }
    
    function second() {
      console.log('Inside second function');
    }
    
    first();
    console.log('Inside Global Execution Context');
    Copy the code

    Functional programming

    Returns the directory

    Functional Programming (FP).

    Functional programming: through the separation of object-oriented programming code, each function is independent, so as to achieve functional independence, easy to reuse and other purposes.

    Example: Code conversion

    ['john-reese'.'harold-finch'.'sameen-shaw'] 
    / / convert
    [{name: 'John Reese'}, {name: 'Harold Finch'}, {name: 'Sameen Shaw'}]
    Copy the code

    Convert the above code.

    const arr = ['john-reese'.'harold-finch'.'sameen-shaw'];
    const newArr = [];
    for (let i = 0, len = arr.length; i < len ; i++) {
      let name = arr[i];
      let names = name.split(The '-');
      let newName = [];
      for (let j = 0, naemLen = names.length; j < naemLen; j++) {
        let nameItem = names[j][0].toUpperCase() + names[j].slice(1);
        newName.push(nameItem);
      }
      newArr.push({ name : newName.join(' ')}); }return newArr;
    Copy the code

    In this code, there are two parts:

    1. Split the string in the array and turn the string into a name.john-reese -> John Reese
    2. Convert an array to an object.['John Reese'] -> [{ name: 'John Reese' }]

    So we can change it directly:

    / * * *@name Change the way names are displayed *@param {array} Arr Specifies the array that needs to be changed@param {string} Type Supports name */ in different formats
    const changeName = (arr, type) = > {
      return arr.map(item= > item.split(type).map(name= > name[0].toUpperCase() + name.slice(1)).join(' '));
    };
    
    / * * *@name Array is changed to object *@param {array} Arr Specifies the array that needs to be changed@param {string} What field * does the key correspond to@return {object} Returns the changed object */
    const arrToObj = (arr, key) = > {
      return arr.map(item= > ({ [key]: item }));
    };
    
    const result = arrToObj(changeName(['john-reese'.'harold-finch'.'sameen-shaw'].The '-'), 'name');
    console.log(result); // [ { name: 'John Reese' }, { name: 'Harold Finch' }, { name: 'Sameen Shaw' } ]
    Copy the code

    Hey, isn’t that functionality encapsulation? Typically, code that appears more than two times in the work is encapsulated.

    Functional programming is to extract and encapsulate all functions that can be extracted.

    As if to grasp the truth here, Jsliang did not understand the definition of sa in detail, hope not misleading.

    13.1 Features of functional programming

    Returns the directory

    1. Functions are first-class citizens. You can take advantage of that to make it extractable.
    2. Declare a time to do something. Functional programming mostly declares what a function needs to do, not how it does it.
    3. Easy for garbage collection. The variables inside the function facilitate garbage collection, do not produce too many variables, and the user does not need a lot of definition.
    4. Data is immutable. Functional programming requires that all data be immutable, and if an object needs to be modified, it should be created and modified, rather than contaminating the original data.
    5. Stateless. The same function returns the same output for the same input whenever it is run, independent of changes in the external state.
    6. No side effects. Function A should be just for the sake of its implementation and not change with external changes, so that when it is finished, its internal data can be recycled. And it does not modify the parameters passed in.

    Pay attention to the passing of reference values (Object, Array) and try not to contaminate the incoming data.

    13.2 pure functions

    Returns the directory

    The concept of a pure function has two points:

    1. Independent of external state (stateless): The result of a function does not depend on a global variable,thisA pointer,IOOperation, etc.
    2. No side effects (unchanged data) : do not modify global variables, do not modify the incoming parameters.

    Advantages:

    • Easy to test and optimize
    • The cache can be
    • Since the document
    • Fewer bugs

    Progressive Web Applications (PWA)

    Returns the directory

    Progressive Web Applications (PWA) is a concept Google introduced in late 2015. It’s basically a Web application, but looks and feels like a native App. Pwa-enabled websites can provide functions such as offline work, push notifications, and access to device hardware.

    14.1 the advantages

    Returns the directory

    • Smaller, Faster: Progressive Web applications are much smaller than native applications. They don’t even need to be installed. They do not waste disk space and load very fast.
    • Responsive Interface: PWA-enabled web pages can automatically adapt to various screen sizes. It can be a phone, tablet, desktop or laptop.
    • No Updates: Most mobile applications require regular weekly updates. Like a regular website, the PWA always loads the latest update whenever a user interaction occurs and does not require application or game store approval.
    • Cost-effective: Native mobile apps need to be developed separately for Android and iOS devices, which can be very expensive to develop. The PWA, on the other hand, has the same functionality, but at a fraction of the previous price and is less expensive to develop.
    • SEO advantage: Search engines can find PWA and load very fast. Just like any other site, links can be shared. Provide a good user experience and results, improve your SEO ranking.
    • Offline functionality: PWAs can be accessed offline or over a low Internet connection due to support from the Service Worker API.
    • Security: THE PWA is passed over HTTPS connections and protects user data during each interaction.
    • Push Notifications: With push notification support, PWA can easily interact with users and provide a great user experience.
    • Bypassing the App Store: Native apps that require any new updates need to be approved by the App Store in a few days and have the possibility of being rejected or banned. For this, PWA has the unique advantage of not requiring App Store support. The updated version can be loaded directly from the Web server without App Store approval.
    • Zero installation: While browsing, PWA will have its own icon on phones and tablets, just like mobile apps, but without the lengthy installation process.

    14.2 disadvantages

    Returns the directory

    • Low access to system functions: Currently the PWA has limited access to native system functions compared to native apps. Also, none of the browsers support all of its capabilities, but it may become the new development standard in the near future.
    • Most Android, a few iOS: More support now comes from Android. IOS provides only part of it.
    • No review criteria: THE PWA does not require any review applicable to native apps in the app Store, which may speed up the process, but lacks the benefit of promotion from the app store.

    Xv Standardization

    Returns the directory

    CommonJS specification, AMD specification, CMD specification, ES6 Modules specification these 4 are front-end normalization content, so what is the difference between them?

    In the absence of these, we passed:

    • A function is a module.function fn() {}
    • An object is a module.let obj = new Object({ ... })
    • Execute the function immediately (IIFE).(function() {})()

    15.1 CommonJS specification

    Returns the directory

    After that, we have the CommonJS specification, which we see a lot of, the Same as Node:

    • Export:module.exports = {},exports.xxx = 'xxx'
    • Import:require(./index.js)
    • Search mode: Search for files in the current directory. If no files exist, search for files in the current directorynode_modulesFile. No more, bubbling queries, all the way into the systemnpmDirectory lookup.

    It features:

    1. All code runs within the module scope and does not contaminate other files
    2. requireThe value you get is a copy of the value, that is, you refer to a variable in another JS file, the operation will not affect the other files

    It has its own drawbacks:

    1. Application level. inindex.htmlIn doingvar index = require('./index.js')The operation reported an error because it was ultimately executed in the background and could only beindex.jsreferenceindex2.jsThis way.
    2. Synchronous loading problem.CommonJSModules are loaded synchronously in the specification, i.eindex.jsIn the loadindex2.jsIf theindex2.jsIt’s stuck. That’s a long wait.

    15.2 AMD specification

    Returns the directory

    Why is there an AMD specification?

    Answer: The CommonJS specification is useless:

    1. Applicable client
    2. Waiting to load (synchronous load problem).

    So what does it do?

    Modules can be loaded asynchronously. AMD is short for Asynchronous Module Definition. Remember that async is Asynchronous.

    15.3 CMD specification

    Returns the directory

    CMD (Common Module Definition), which is the standard recommended by SeaJS, relies on the nearest and requires it when used.

    The biggest difference between AMD and CMD is the execution timing of the dependent module. Note that it is not the timing or the way of loading the module. Both load modules asynchronously.

    15.4 ES6 Modules specifications

    Returns the directory

    • Export:
    1. export a
    2. export { a }
    3. export { a as jsliang }
    4. export default function() {}
    • Import:
    1. import './index'
    2. import { a } from './index.js'
    3. import { a as jsliang } from './index.js'
    4. import * as index from './index.js'

    Features:

    1. exportCommands andimportCommands can appear anywhere in the module, as long as they are at the top of the module. If it is in the block-level scope, an error will be reported because it is not possible to do static optimizations in a block of conditional code, which is contrary to the design of the ES6 module.
    2. importThe command is promoted to the head of the entire module and is executed first.

    CommonJS:

    • CommonJSModules are loaded at runtime,ES6 ModulesIs a compile-time output interface
    • CommonJSThe output is a copy of the value;ES6 ModulesThe output is a reference to the value, and changes within the output module affect the reference
    • CommonJsThe imported module path can be an expression because it uses therequire()Methods; whileES6 ModulesIt can only be strings
    • CommonJS thisPoints to the current module,ES6 ModulesthisPoint to theundefined
    • ES6 ModulesNone of these top-level variables exist in:arguments,require,module,exports,__filename,__dirname

    How Babel is compiled

    Returns the directory

    • babylonES6/ES7The code parses intoAST
    • babel-traverseASTDo the traversal translation to get the newAST
    • newASTthroughbabel-generatorConverted toES5

    Jsliang doesn’t go too far into this one, but it’s easy to understand:

    1. Black and white tangram shapes that can be broken down to produce parts (ES6/ES7Parsed intoAST)
    2. Replace these parts with colored ones (ASTCompile to newAST)
    3. Assemble colored parts into new shapes (ASTconvertES5)

    Seventeen problem set

    Returns the directory

    17.1 Common apis for Arrays

    Returns the directory

    • push: Adds an element to the end of an array
    • unshift: Adds elements to the array header
    • pop: Removes an element from the end of an array
    • shift: Removes elements from the array header
    • splice: Deletes an array element
    • slice: Intercepts array elements
    • indexOf: Finds the first occurrence of an element
    • lastIndexof: Finds the last occurrence of an element
    • findIndex: Finds the first occurrence of the element
    • forEach: Iterates over elements
    • map: Iterates over elements
    • filter: Filter elements
    • some: Contains an element
    • every: All elements are consistent with an element
    • includes: checks whether an element is included
    • concat: Merge elements
    • join: Merges elements into a string
    • toString: becomes a string
    • sort: Element sorting

    17.2 Common DOM apis

    Returns the directory

    • To obtain
    • create
    • add
    • delete
    // Get the element
    const node = document.getElementById(id); / / or querySelector (". The class | | # id name ");
    
    // Create the element
    const heading = document.createElement(name); // name: p, div, h1...
    heading.innerHTML = ' ';
    
    // Add the element
    document.body.appendChild(heading);
    
    // Delete the element
    document.body.removeChild(node);
    Copy the code

    17.3 De-Duplicating arrays

    Returns the directory

    Array deduplication is a point often mentioned:

    const arr = [1.1.2.3.3];
    // Expect: [1, 2, 3]
    
    // Method 1: for with new array interception
    const newArr1 = [];
    for (let i = 0; i < arr.length; i++) {
      if (!newArr1.includes(arr[i])) {
        newArr1.push(arr[i]); 
      }
    }
    console.log('newArr1:', newArr1);
    
    // Method 2: Use Set
    const newArr2 = [...new Set(arr)];
    console.log('newArr2:', newArr2);
    
    // Method 3: use filter
    const newArr3 = arr.filter((item, index) = > arr.lastIndexOf(item) === index);
    console.log('newArr3:', newArr3);
    Copy the code

    One interesting question I encountered in an interview was: do not use the array API for deduplicating.

    Note: You cannot use apis such as Push, indexOf, etc

    17.4 Digital amount

    Returns the directory

    • Method one: violent traversal
    const num = String(1234567890);
    let result = ' ';
    
    for (let i = num.length - 1; i >= 0; i--) {
      if(i ! == num.length -1 && i % 3= = =0) {
        result = num[i] + ', ' + result;
      } else{ result = num[i] + result; }}console.log(result);
    Copy the code
    • Method two: API tricks
    console.log(
      String(1234567890).split(' ').reverse().reduce((prev, next, index) = > (index % 3) = = =0 ? next + ', ' + prev : next + prev)
    );
    Copy the code
    • Method three: API tricks
    console.log(
      (1234567890).toLocaleString('en-US'));Copy the code
    • Method 4: Regular expression
    String(1234567890).replace(/\B(? =(\d{3})+(? ! \d))/g.', ');
    Copy the code

    17.5 Traversal Problem

    Returns the directory

    When the following code is executed, what is the result of the array?

    let array = [ , 1.2.3];
    array = array.map((i) = > ++i)
    Copy the code
    • A:[, 2, 3, 4]
    • B:[NaN, 2, NaN, 3, NaN, 4]
    • C:[1, 2, 1, 3, 1, 4]
    • D:[null, 2, null, 3, null, 4]

    Answer: A,

    Explanation:

    1. forEach(),filter(),reduce(),every()some()They jump over the space.
    2. map()The space is skipped, but the value is retained
    3. join()toString()Will treat the empty space asundefinedAnd theundefinednullWill be processed as an empty string.

    17.6 setTimeout

    Returns the directory

    for (var i = 0; i < 5; i++) {
      setTimeout(() = > {
        console.log(i);
      }, 1000);
    }
    Copy the code

    The execution result of the above code?

    • A: Five five five five five five
    • B: 0 0 0 0 0 0
    • C: 0 1 2 3 4
    • D: 1 2 3 4 5

    Answer: A,

    Resolution:

    1. var iforCan contaminate variables and cause a global traversalitheiAt the end of the run, it’s going to be5
    2. setTimeoutIs the macro task inscriptThis macro task was executed after the completion of the execution, so the collectioni5
    3. The final output is 55

    17.7 requestAnimationFrame

    Returns the directory

    for (let i = 0; i < 5; i++) {
      requestAnimationFrame(() = > {
        console.log(i);
      });
    }
    Copy the code

    Execution result of the above code:

    • A: One, two, three, four, five
    • B: 0 1 2 3 4
    • C: 4, 4, 4
    • D: 5, 5, 5, 5

    Answer: B

    Resolution:

    1. let i 使 forForm block-level scope.
    2. requestAnimationFrameSimilar to thesetTimeout, but it can be viewed as a microtask, a method that is called after the execution of the microtask queue, but before performing UI rendering.
    3. So this question doesn’t meanrequestAnimationFrameWill collecti, butletCreates a block-level scoping problemvar iAnd output 5 as usual5.

    17.8 Temporary dead zone

    Returns the directory

    1. What does the following code output?

    let a = 1;
    let test = function() {
      console.log(a);
      a++;
    }
    test();
    Copy the code

    2. What does the following code output?

    let a = 1;
    let test = function() {
      console.log(a);
      let a = 2;
      a++;
    }
    test();
    Copy the code

    The answer:

    The first question output: 1

    Uncaught ReferenceError: Cannot access ‘a’ before initialization

    Resolution:

    The reason for this is that in the same block, the let is redefined later, so the variable cannot be referenced earlier. Also, you cannot take the value of the nested outer layer.

    17.9 Output The Printed Result

    Returns the directory

    function sayHi() {
      console.log(name);
      console.log(age);
      var name = "Lydia";
      let age = 21;
    }
    
    sayHi();
    Copy the code

    The output of the above code?


    Answer: undefined, error

    Resolution:

    This problem is changed to see:

    function sayHi() {
      var name; // Variable promotion - variable declaration
      console.log(name); // undefined
      console.log(age); // Let has a temporary dead zone, and the variable will not be promoted
      name = "Lydia"; // Variable promotion - variable assignment
      let age = 21;
    }
    
    sayHi();
    Copy the code

    17.10 Output The Printed Result

    Returns the directory

    function myFunc() {
      console.log(a);
      console.log(func());
    
      var a = 1;
      function func() {
        return 2;
      }
    }
    
    myFunc();
    Copy the code

    What is output?


    Answer: undefined 2

    It’s not difficult

    17.11 the Event Loop

    Returns the directory

    for (var i = 0; i < 3; i++) {
      setTimeout(() = > console.log(i), 1);
    }
    
    for (let i = 0; i < 3; i++) {
      setTimeout(() = > console.log(i), 1);
    }
    Copy the code

    The output of the above code?


    The answer is:

    (1) var is contaminated in for (2); (2) setTimeout (3, 3); (3, 3, 3

    I is a new value for each iteration, and each value exists in the block-level scope of the loop, so output 0, 1, 2

    17.12 Producing the Printed Result

    Returns the directory

    let date = new Date(a);for (var i = 0; i < 5; i++) {
      setTimeout(function() {
        console.log(new Date - date, i); / / 1
      }, 1000);
    }
    
    console.log(new Date - date, i); / / 2
    Copy the code

    What is output?


    The answer:

    05 1001 5 1004 5 1005 5 1006 5 1007 5Copy the code

    A. date b. date C. date D. date

    Then 5 macro tasks, all of them are timer setTimeout, so they will be executed later, output: 1000 5, but the timer is not always on time, so it could be 1001, 1002 or something else.

    17.13 Make a == 1 && a == 2

    Returns the directory

    Try encoding such that: if(a == 1 && a == 2 && a == 3) {} This case holds.

    • Methods a

    When casting, we know how an object is converted to its original data type. If [Symbol. ToPrimitive] is deployed, the return value of Symbol. ToPrimitive is returned.

    Of course, we can also deploy this function on the valueOf or toString interfaces, and the effect is the same.

    // Use closures to extend scope
    let a = {
      [Symbol.toPrimitive]: (function () {
        let i = 1;
        return function () {
          returni++; }}}) ()Copy the code
    • Method 2

    Define a property on window/global using object.defineProperty. When a property is obtained, get is called

    let val = 1;
    Object.defineProperty(window.'a', {
      get: function() {
        returnval++; }});Copy the code
    • Methods three
    var a = [1.2.3];
    a.join = a.shift;
    Copy the code

    The toString method of an array returns a string consisting of the return value of toString() for each element in the array joined (separated by commas) by calling the join() method.

    Therefore, we can re-join the method. Return the first element and remove it.

    18 More

    Returns the directory

    There are a lot of basic knowledge, or topics, Jsliang did not have the energy to add one by one, try to put the original text in the article.

    • Here are 43 JavaScript interview questionsReading Advice: 1 hour

    This is a good article, jsliang still made some mistakes in the first time, haha.

    So this article is over, I wish my partners to find the right Offer as soon as possible.




    Jsliang’s document library 由 Liang JunrongusingCreative Commons Attribution – Non-commercial – Share in the same way 4.0 International licenseLicense.

    Based on the
    Github.com/LiangJunron…On the creation of works.

    Permissions outside of this license agreement may be obtained from
    Creativecommons.org/licenses/by…Obtained.