What is the
Collect and organize some code blocks, interview questions, strengthen understanding and memorization
The title
- Verify that the parameter is a number
- Disable right-click in web pages
- What is the AJAX
- How do I cancel the Promise request
- How do I cancel an Axios request
- Promises and observables what is the difference between Promises and observables
- How do you create a copy to Clipboard button
- What is the shortcut to get the timestamp
- How do you flatten a multidimensional array
- Multicondition check
- Capture the browser back button
- What is a wrapper object
- What is the minimum timeout limit
- What are microtasks
- What is an event table
- How do I use javascript libraries in typescript files
- What is the Babel
- Is Node.js completely single-threaded
- What is a RxJS
- What is a short circuit
- What is an asynchronous function
- How do I make objects iterable in javascript
- How do I check if an object is a Promise
- What is the difference between arguments objects and REST parameters
- What is a built-in iterable
- The for… Of and the for… What are the differences between in statements
- How do I call IIFE without any extra parentheses
- What’s the easiest way to ignore promise errors
- How to check regular expression
- When do you use function components and when do you use class components when developing with React
- How to do adaptive image layout
Verify that the parameter is a number
function isNumber (n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
Copy the code
Disable right-click in web pages
<body oncontextmenu="return false">
Copy the code
How do you create a copy to Clipboard button
document.querySelector('#copy').onclick = function () {
document.querySelector('input').select()
document.execCommand('copy')}Copy the code
What is the AJAX
Asynchronous retrieval techniques allow us to retrieve data without refreshing the pageCopy the code
How do I cancel the Promise request
1.Returning the pending status cancels the requestPromise.resolve().then((res) = > {
console.log("Performing")
return new Promise(() = >{})
}).then(() = > {
// Subsequent functions will not be called
console.log('ok2')
}).catch(err= > {
console.log('err->', err)
})
2.throughthrow 'throw error1'cancelPromise.resolve().then(() = > {
console.log('ok1')
throw 'throw error1'
}).then(() = > {
console.log('ok2')},err= > {
// Catch an error
console.log('err->', err)
}).then(() = > {
// This function will be called
console.log('ok3')
throw 'throw error3'
}).then(() = > {
// The function before the error is caught will not be called
console.log('ok4')
}).catch(err= > {
console.log('err->', err)
});
Copy the code
How do I cancel an Axios request
1.The first creates the Cancel token through the canceltoken. source factory methodvar CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// Processing error}});// Cancel the request (the message argument is optional)
source.cancel('Operation canceled by the user.');
2.The Cancel token is created by passing the Executor function to the CancelToken constructorvar CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// The executor function takes a cancel function as an argumentcancel = c; })});// Cancel the request
cancel();
Copy the code
Promises and observables what is the difference between Promises and observables
Promises only issue one value at a time and call immediatelyPromiseAlways asynchronous, even though it resolves immediately without providing any operators that cannot be canceled, observables can only simulate the exception of canceling to emit multiple values over a period of time (from0To multiple value streams) lazy by nature; They need to call a subscription Observable, which can be synchronous or asynchronous, to provide operators such as map, forEach, filter, reduce, Retry, retryWhen, and so on, unsubscribe()Copy the code
What is the shortcut to get the timestamp
var _date = +new Date(a)var _date = Date.now()
Copy the code
How do you flatten a multidimensional array
const _array = [11[22.33], [44.55], [66.77].88.99]
constflattenArr = [].concat(... _array)// [11, 22, 33, 44, 55...
Copy the code
Multicondition check
if(["val1"."val2"].indexOf(input) ! = = -1) {... }Copy the code
Capture the browser back button
// Capture the browser back button event
window.onbeforeunload = function () {... };Copy the code
What is a wrapper object?
In addition tonull 和 undefinedEvery primitive outside of this has a wrapper object, and the list of wrapper objects isString,Number,Boolean,Symbol 和 BigInt.Copy the code
What is the minimum timeout limit
Both the browser and NodeJS javascript environment are greater than0Millisecond minimum delay for throttling, even if set0The millisecond delay also does not occur immediately. You cannot use it due to a minimum delay greater than 0mssetTimeout(fn, 0) Execute the code immediately. But you can use itwindow.postMessage() to implement this behavior.Copy the code
What are microtasks
Microtask: it is the current task to be executed in the queue. After the completion of the microtask, the javascript code of the main task will be executed immediately. While the microtask is executing, the main thread is blocked until the microtask queue is empty. The main source of microtasks isPromiseResolve,Promise. Reject, MutationObservers, IntersectionObservers, etc.Copy the code
What is an event table
An event table is a data structure used to store and track all events that will be executed asynchronously after an interval or after some API request is resolved. That is, it is added to the event table every time you call the setTimeout function or invoke an asynchronous operation. It doesn't perform functions on its own. The main purpose of an event table is to track events and send them to an event queue.Copy the code
How do I use javascript libraries in typescript files
Not all JavaScript libraries or frameworks have TypeScript declaration files. But if you still want to use libraries or frameworks in our TypeScript files without compile errors, the only solution is declare keywords and variable declarations.Copy the code
What is the Babel
Babel is a JS translator that converts ES2015 + code into backwards-compatible JS codeCopy the code
Is Node.js completely single-threaded
Node is single-threaded, but some of the functions contained in the Node.js standard library (such as the FS module functions) are not single-threaded. That is, their logic runs outside of the single node.js thread to improve the speed and performance of the program.Copy the code
What is a RxJS
RxJS (Reactive Extensions forJavaScript) is a library that uses observables for reactive programming, making it easier to write asynchronous or callback-based code. It also provides utility functions for creating and using Observables.Copy the code
What is a short circuit
ifBecause of the left-to-right nature of logical operations,ifFlag && go();Copy the code
What is an asynchronous function
Asynchronous functions are one useasyncKeyword declared functions, which are written asynchronously in a more concise style. These functions can contain zero or moreawaitExpression.Copy the code
How do I make objects iterable in javascript
Can be achieved bySymbolIterator defines attributes on which to make the object iterable.const collection = {
one: 1.two: 2.three: 3[Symbol.iterator]() {
const values = Object.keys(this);
let i = 0;
return {
next: () = > {
return {
value: this[values[i++]],
done: i > values.length } } }; }};const iterator = collection[Symbol.iterator]();
console.log(iterator.next()); // → {value: 1, done: false}
console.log(iterator.next()); // → {value: 2, done: false}
console.log(iterator.next()); // → {value: 3, done: false}
console.log(iterator.next()); // → {value: undefined, done: true}
Copy the code
How do I check if an object is a Promise
function isPromise (object) {
return Boolean(object && typeof object.then === 'function')}Copy the code
What is the difference between arguments objects and REST parameters
1.argumentsObject is an array-like object, but not an array. The rest argument is an array instance.2.argumentsObjects do not support methods such as sort, map, forEach, or POP. These methods can be used for REST parameters.3.Rest parameters are just parameters that are not given individual names, and parameter objects contain all the parameters that are passed to the functionCopy the code
What is a built-in iterable
1.Arrays and type arrays2.String: Iterates over each character or Unicode code point3.Maps: Iterate over its key-value pairs4.Collections: Iterate over their elements5.Arguments: Special array-like variables in a function6.DOM collection such as NodeListCopy the code
The for… Of and the for… What are the differences between in statements
1. for. In iterates over all enumerable property keys of an object2. for. Of iterates over the value of the iterable.Copy the code
How do I call IIFE without any extra parentheses
Call function Expression immediately (IIFE) requires a pair of parentheses to wrap the function containing the statement set. As a result of IIFE andvoidOperators discard the result of expressions, so we can change it to:void function(dt) {
console.log(dt.toLocaleTimeString()); } (new Date());
Copy the code
What’s the easiest way to ignore promise errors
await promise.catch(e= > void e)
Copy the code
How do I style console output using CSS
console.log(
'%cThis is a red text with bigger font'.'color:red; font-size:20px'
)
Copy the code
How to check regular expression
A - Matches a character a(not b, aa, etc.). ABC -- matches a, followed by B, and finally C. A * -- matches0One or more characters in a (+ represent at least match one or more). [^ a] - match one character at a time, but it can't be a. a | b - match one character a or b. [ABC] - match one character at a time, it can be a, b or c. [ABC] ^ - match one character at a time, But it cannot be a, B, or C. [a-z] -- Matches characters a-Z and all lowercase (you can use [A-za-z] to cover case, or [a-z] to limit capitalization).a.c -- matches character A, matches any character in the middle, and matches character C. A {5} - Matches character a five times. A {5.7} -- Matches character a five to seven times, no more or less.Copy the code
When do you use function components and when do you use class components when developing with React
1.Use functions whenever you can; Hooks split recombination ratio for logicclassMuch more convenient; 2. If it is not affectedDOMHierarchy, the number of lines of code to a certain level can be dismantled components as far as possible; 3. There areError BoundaryIf you want, this ishooksWhat we can't do now, we have to passHoCorclass component; 4. Not anymoreclass XXX extend React.ComponentI'm used to it. All of itfunction
Copy the code
How to do adaptive image layout
Image adaptation, unchanged aspect ratio, does not affect other layouts. Img-wrapper {position:relative;
width: 100%;
padding-bottom: 75%;
}
.img-wrapper img {
position:absolute;
width: 100%;
height: 100%;
}
Copy the code