TOC

  • 📝 🎉 ~ (0x01-0x20)
  • > 📝 🎉 ~ (0x21-0x40)
  • 📝 🎉 ~ (0x41-0x60)
  • 📝 🎉 ~ (0x61-0x80)

rememberThree consecutive + attentionWhoa ~

0x21 What is Post Message

The postMessage() method of the Worker interface can send a message to the Worker’s internal scope with the argument that this is the data to be sent to the Worker. The data can be any value or JavaScript object processed by a structured clone algorithm, including circular references.

The Worker can use DedicatedWorkerGlobalScope. PostMessage method sends the information to generate its thread.

// Worker thread:
worker.postMessage({
    msg: "From Worker thread"}); worker.onmessage =(event) = > {
    console.log("Main thread:" + event.data);
};

var worker = new Worker("./worker.md.js");
worker.postMessage("From main thread");
worker.onmessage = (event) = > {
    console.log("Worker thread:" + event.data);
};
Copy the code

0x22 What is the function of the double exclamation mark?

Double exclamation mark (ie. Double negative,!!) The ability to ensure that the result type is Boolean. If it is false (e.g. 0, null, undefined, etc.), it will be false, otherwise true.

For example, we can test the IE version with the following expression:

let isIE8 = false; isIE8 = !! navigator.userAgent.match(/ / MSIE 8.0);
console.log(isIE8); // true / false
Copy the code

If double negation is not used, the original value is returned:

console.log(navigator.userAgent.match(/ / MSIE 8.0)); // Array [] / null
Copy the code

Tip:!!!!! Not a new operator, just two negation operators!

0x23 What is the DELETE operator?

The delete keyword can be used to delete an Object property or value:

let user = { name: "John".age: 20 };
delete user.age;

console.log(user); // {name: "John"}
Copy the code

What is 0 x24typeofThe operator

The typeof operator returns a string indicating the typeof a variable or expression. All possible outputs are as follows:

type The results of
Undefined “undefined”
Null “Object” (see below)
Boolean “boolean”
Number “number”
BigInt (new in ECMAScript 2020) “bigint”
String “string”
Symbol (new in ECMAScript 2015) “symbol”
Function object (implemented according to ecMA-262 specification [[Call]]) “function”
All other objects “object”

24.1 typeof null

console.log(typeof null); // "object"
Copy the code

In the original implementation of JavaScript, values in JavaScript were represented by a tag representing a type and actual data values. The type label of the object is 0. Because null represents a null pointer (with a value of 0x00 on most platforms), null has a type label of 0 and typeof NULL therefore returns “object”.

0x25 What is the difference between window and Document? BOM and DOM?

First, the logic between the two is: window -> document.

25.1 windowobject

Window is the global this pointer in the browser that represents an open window or frame in the browser. The window object is automatically created at or every time it appears. The window object implements global properties and methods defined by the core JavaScript, such as window.alert(), window.print()…

25.2 documentobject

Represents the entire HTML document and can be used to access all elements in the page, which can be accessed through the window.document property.

25.3 BOM Browser Object Model

Provides objects that interact with a browser window independent of the content. It describes the method and interface of interaction with the browser. It can access and operate the browser window. For example, it can pop up a new window and change the text in the status bar.

25.4 DOM Document Object Model

DOM is a tree-based API for HTML. DOM describes the methods and interfaces used to process web content. DOM is the API of HTML. DOM plans the entire page into a document composed of node hierarchy.

Note: DOM and BOM are only available when the JS host environment is a browser, not in Node.

graph TB; window ---> document e["frames[]"] --> window history --> window location --> window navigator --> window screen --> window dot2[...]  --> window subgraph DOM a["anchors[]"] --> document b["forms[]"] --> document c["applets[]"] --> document d["images[]"]  --> document dot[...]  --> document end

0x26 How Do I Access TAB History?

We can go directly to window.history to get the browser history, where:

  • length: Length of history to access the current TAB page.
  • back(): return to previous page, equivalent towindow.history.go(-1).
  • forward(): Go to the next page (if present), equivalent equivalentwindow.history.go(1).
  • go(n): Goes to the NTH record (relative to the current record).
  • pushState(): Push the browser history.
  • replaceState(): Updates the latest record to the given data.

0x27 How Do I Check the Status of Upper and Lower Case Keys?

KeyboardEvent provides us with access to sensitive API: KeyboardEvent. Prototype. GetModifierState (” CapsLock “), we directly use the following code:

document.addEventListener("keydown".(event) = > {
  console.log(event.getModifierState("CapsLock"));
});
Copy the code

0x28 NaN, isNaN, and Number.isNaN?

NaN is a property of a global object; in other words, it is a global variable.

NaN’s indication is not a Number — the same value as number.nan. NaN is a non-configurable, non-writable property in modern browsers. Even if this is not the case, avoid overwriting it. NaN is rarely used in programs.

There are five different types of operations that return NaN:

  • Unable to parse numbers (e.gparseInt("blabla")Number(undefined))
  • Mathematical operations whose results are not real numbers (e.gMath.sqrt(-1))
  • The operand of the argument isNaN(e.g.7 ** NaN)
  • Indeterminate forms (e.g0 * InfinityOr,undefined + undefined)
  • Any operation involving strings that is not an addition operation (e.g"foo" / 3)

The isNaN method is not the same as number. isNaN, where isNaN is a global method and only determines if the parameter is not a Number, while number. isNaN only passes NaN (a specific value) as follows:

console.log(Number.isNaN({})); // false
console.log(isNaN({})); // true
console.log(Number.isNaN(NaN)); // true
console.log(isNaN(NaN)); // true
Copy the code

0x29 What is event Flow? What is event broker? What is event bubbling? What is event capture?

Event flow actually refers to the process of event transfer between document and target node, as shown in the figure below:

Graph of TD document -- -- > capture | | HTML HTML - > capture | | body body - > capture | | div div - > capture | | TextNode TextNode - > bubble | | div div - > bubble | | Body body - > bubble | | HTML HTML - > bubble | | the document

29.1 Event bubbling and capture

Event bubbling is a stream of events that propagates from the bottom up, from the target-triggered element up to the Window object.

graph BT; TextNode - > bubble | | div div - > bubble | | body body - > bubble | | HTML HTML - > bubble | | the document

Event capture is also a stream of events, but it works from top to bottom, from the Window object all the way to the target-triggered element.

graph TB; Capture document -- - > | | HTML HTML - > capture | | body body - > capture | | div div - > capture | | TextNode

29.2 Event Delegation

If there are multiple DOM nodes that need to listen for events, attaching a listener function to each DOM binding can have a significant impact on page performance because we can optimize it through event delegates. Event delegation takes advantage of the bubbling principle.

For example, there is a very long ul> Li list.

<ul id="list">
  <li class="item"></li>
  <li class="item"></li>
  <li class="item"></li>
  <li class="item"></li>
  <li class="item"></li>
  <li class="item"></li>
  <li class="item"></li>
  <li class="item"></li>
  <li class="item"></li>
</ul>
Copy the code

To listen for the click event, we just need:

const list = document.getElementById("list");
list.addEventListener("click".(ev) = > {
  console.log(ev.target); // [Element] <li class="item">
});
Copy the code
  • ev.target: Triggers the event element.
  • ev.currentTarget: The element that binds the event.

Using event delegates, you can obviously do this:

  • Dynamic listening:You can use event delegatesAutomatic bindingDynamically added elements do not need to be bound to the nodeonclickSuch events.
  • Improved performance: Save on performance costs and code usage.

0x30 How Do I confirm and send a Form?

.submit() :

form.submit();
Copy the code

0x31 OnLoad, onReadyStatechange, DOMContentLoaded…… The difference between?

graph TB;
  onpagehide --> onbeforeunload
  onbeforeunload --> onunload
  onunload --> domLoading
  domLoading --> domInteractive
  domInteractive --> readystatechange1[interactive]
  readystatechange1 --> domComplete
  domComplete --> readystatechange2[complete]
  readystatechange2 --> onload
  onload --> onpageshow

0x32 CORS.

First of all, why is there a CORS limit?

— Yes, same-Origin policy in case of CSRF events.

Whenever the browser makes an HTTP request to a field, it carries with it the cookie that the field belongs to. This is useful for functions such as authentication or maintaining sessions. For example, when you get admin permission to visit hoarfroster.space, your browser stores a cookie session= S-admin-1941 for that domain-related session:

graph LR; The client/client hoarfroster. Space "-- -- > | usrname =... &pwd=... | site["hoarfroster.space"] site -->|Set-Cookie: session=s-admin-1941| client

And if I’m on a pirate site right now… Access hoarfroster.space with XMLHttpRequest If there were no CORS restrictions…

Browsers carry cookies!

graph LR; Client/client "hacker.com"] -- > | session = s - admin - 1941 | site/" hoarfroster. Space"

What the hell? Hacker.com can also get my admin privileges??

32.1 Same-origin Policy

Each time a request is made, the browser verifies that the link addresses match. Access-control-allow-origin = access-Control-allow-origin = access-Control-allow-origin = access-Control-allow-origin = access-Control-allow-origin

  • Access-Control-Allow-Origin: hacker.com: Allows cross-domain access to hacker.com.
  • Access-Control-Allow-Origin: *: Allows cross-domain access to all web sites.

32.2 Solutions

  1. Adding a serverAccess-Control-Allow-Origin: hacker.com.
  2. Use a server proxy (same-origin policy only limits browser -> server, not server -> server).
  3. JSONP (see #91).

0x33 What is an event?

Event refers to a specific moment. In the front end, it refers to some specific interaction moments that occur in the document or browser, such as onMessage event of PostMessage, onclick event, onKeyDown event of input, onreSize event of changing window size, etc.

Event handling is the behavior of the browser to respond to an event when it is triggered, and the corresponding code for this behavior is the event handler.

0x34 preventDefault, stopImmediatePropagation and stopPropagation are what?

The former is used to block the default behavior of the event, such as I want to disable the right-click menu:

document.body.oncontextmenu = (evt) = > evt.preventDefault();
Copy the code

StopPropagation is used to block propagation of events (including capture and bubbling). In addition, stopImmediatePropagation is used to block the firing of listeners for the current element (which will prevent event propagation as well as the firing of the same event listener on the current element).

0x35 What is PWA?

Progressive Web applications are Web applications that use emerging Web browser apis and capabilities as well as traditional progressive enhancement strategies to bring a user experience similar to native applications to cross-platform Web applications.

The benefits of PWA are as follows:

  1. You can install (Add-to-screen) icon applications.
  2. You can use the Service Worker to handle network requests, cache, and offline use without network conditions.
  3. You can use push and notification apis.
  4. Client storage can be used.
  5. IndexedDB can be used.

0x36 How do I Switch pages?

  1. window.location.href = “hoarfroster.space”
  2. location = “hoarfroster.space”
  3. window.open(“hoarfroster.space”, “_blank”)
  4. window.open(“hoarfroster.space”, “_self”)
  5. Window.location.replace (” Hoarfroster.space “) — Does not keep a history and is non-returnable.
  6. window.location.assign(“hoarfroster.space”)

0x37 How do I determine whether a string contains a specific string or whether a regular expression is satisfied?

37.1 the RegExp

37.1.1 RegExp. Test

console.log(RegExp(/str/).test("strStr")); // true
Copy the code

You can also use RegExp. Exec to determine the length of the array, but this is cumbersome and not very good performance.

console.log(RegExp(/str/).exec("strStr").length > 0); // true
Copy the code

37.1.2 String. The match

console.log("strStr".match("str")! = =null); // true
Copy the code

37.1.3 String.search

console.log("strStr".search(RegExp(/str/))! = = -1); // true
Copy the code

37.2 the String

37.2.1 String. IndexOf ()

console.log("strStr".indexOf("str")); // true
Copy the code

37.2.2 String.search

console.log("strStr".search("str")! = = -1); // true
Copy the code

37.2.3 String. The match

console.log("strStr".match("str")! = =null); // true
Copy the code

0x38 Various Loops of JavaScript?

For different purposes, we can actually talk about it in several parts:

  • Pure loop (pure number loop)
  • Array traversal
  • Array assignment
  • Array modification (original array modification)
  • An array of screening

The for loop also has many variations, such as for, for (in reverse order), for… Of, for, for… In, for… Await.

In terms of performance, loops actually run at quite different speeds across platforms and browsers.

0x39 How can I Tell if an object is empty?

39.1 the for – in

According to the for… In traverses the object, returning true if it exists and false otherwise

function test(obj) {
  for (let i in obj) {
    return true;
  }
  return false;
}
Copy the code

39.2 JSON. Stringify

Use JSON’s json.stringify () method to find out if it is a string {}

function test(obj) {
  if (JSON.stringify(obj) === "{}") {
    return true;
  }
  return false;
}
Copy the code

39.3 Object. Keys

We can also use ES6 object.keys () to determine:

const test = (obj) = > (Object.keys(obj).length === 0 ? true : false);
Copy the code

0x40 What are arguments?

Arguments is an array-like object local variable corresponding to arguments passed to functions other than the arrow function. We can use arguments objects to refer to arguments in functions.

Arguments is not an Array but similar to Array, meaning there are no methods like forEach, map, etc., only length.

Tip: If you are writing ES6-compatible code, you should use the Rest parameter.

40.1 Performance Issues

There are multiple actions that use arguments that can cause functions to fail to optimize, and you have to be very careful when using arguments.

40.1.1 Redefining a named parameter, but using it againarguments

(Note: In non-strict mode)

function defaultArgsReassign(a, b) {
  if (arguments.length < 2) b = 5;
}
Copy the code

One solution is to store parameters as new variables, for example:

function defaultArgsReassign(a, _b) {
  let b = _b;
  if (arguments.length < 2) b = 5;
}
Copy the code

But in the case of the above functions, we usually do this directly:

function defaultArgsReassign(a, b) {
  if (b === void 0) b = 5;
}
Copy the code

There is a problem with arguments, however. If arguments is used after a function, it is easy to forget the previously reassigned object during maintenance, resulting in arguments getting incomplete arguments.

Another solution is to use strict patterns.

40.1.2 leakage of the arguments

function leaksArguments1() {
  return arguments;
}

function leaksArguments2() {
  var args = [].slice.call(arguments);
}

function leaksArguments3() {
  var a = arguments;
  return function () {
    return a;
  };
}
Copy the code

The above three functions leak the Arguments object, making it unrecyclable. Arguments objects should not be passed to other functions or leak out of functions in any other way!

One solution is to create a new array in a loop:

function doesntLeakArguments() {
  // '.length 'is just an integer and does not leak arguments itself
  var args = new Array(arguments.length);
  for (var i = 0; i < args.length; ++i) {
    // I is always the compliant index in the arguments object
    args[i] = arguments[i];
  }
  return args;
}

function anotherNotLeakingExample() {
  var i = arguments.length;
  var args = [];
  while (i--) args[i] = arguments[i];
  return args;
}
Copy the code

It’s a lot more code, but it’s totally worth it. Optimizations, after all, always require more code, which means the semantics can be determined more explicitly.

40.1.3 Reassigning parameters

This code can only be run in non-strict mode:

function assignToArguments() {
    arguments = 3;
    return arguments;
}
Copy the code

Solution: Don’t bother, strict mode just throws errors anyway…

40.2 What is a safe use of arguments

Use only when:

  • arguments.length;
  • Access when I is a compliant indexarguments[i];
  • Never break away.length[i]accessargumentsObject;
  • Strictly usefn.apply(ctx, arguments)I could, but.sliceIt’s wrong!
    • Note that adding attributes to a functionfn.prop = '1') or binding functions (fn.bind()There are hidden classes in the generated new function, and therefore, used in this caseapplyNo longer safe.

Note: In the safe usage above, using Arguments does not cause arguments objects to be allocated.