foreword
Today, let's share with you a ByteDance company - the face of graphite documents! Without further ado, let’s look at the topic first!
topic
one side
- 1. What is the output value of ['10', '10', '10', '10', '10'].map(parseInt)?
- 2. What is your current technology stack? Why use ts?
- 3. The execution process of setTimeout (event loop, synchronous, asynchronous)?
- 4. What is the difference between Promise and async and await? How are async and await implemented?
- 5. Explain requestAnimationFrame/requestIdleCallback, what is the use of each?
- 6. React performance optimization?
- 7. Tell me about your understanding of flex?
- 8. What is reflow and redraw? How to reduce reflow and redraw?
- 9. How to find the reason why the react page is stuck?
10. Programming question: Implement the flatten method of an object, as follows:
const obj = { a: { b: 1, c: 2, d: { e: 5 } }, b: [1, 3, {a: 2, b: 3}], c: 3 }
The result of flatten(obj){} is returned as follows:
// { // 'a.b': 1, // 'a.c': 2, // 'a.d.e': 5, // 'b[0]': 1, // 'b[1]': 3, // 'b[2].a': 2, // 'b[2].b': 3 // c: 3 // }
two sides
- 1. Talk about your understanding of web workers
- 2. What are the advantages of service worker compared to strong cache?
- 3. Talk about your understanding of stack overflow
- 4. What is the sticky in position, and what are the others?
- 5. What do any and unknown mean in ts? How to use generics?
- 6. What is the use of bind? After multiple binds in a row, what does this point to at the end?
- 7. How to implement the plugin of webpack?
- 8. Programming questions:
It is now known that a string is composed of positive integers and four operators (+ - /) of addition, subtraction, multiplication and division. For example, there is a string const str = '11+2-3 4+5/2 4+10/5', now you need to wrap the high-priority operation in parentheses, for example, the result is '11+2-( 3 4)+(5/2*4)+(10/5)'. Note that there may be consecutive multiplication and division operations that need to be wrapped together. Please implement this process with javascript
Three sides
1. Handwritten: Use TypeScript to implement a get function to get its property value
const data = { name: 'tom', age: 18, address: 'xxx' }
- 2. The difference between any and unknown in ts
- 3. Have you used keyof in ts?
- 4. What is the difference between for in/for of?
- 5. Promise value penetration?
answer
one side
1. What is the output value of ['10', '10', '10', '10', '10'].map(parseInt)?
can be converted to:
['10', '10', '10', '10', '10'].map((num, index) => parseInt(num, index))
// [10, NaN, 2, 3, 4]
'10' 0 -> 10: 进制为0,则默认10进制
'10' 1 -> NaN: 1进制不存在
'10' 2 -> 2: 2 * 1 + 2 * 0
'10' 3 -> 3: 3 * 1 + 3 * 0
'10' 4 -> 4: 4 * 1 + 4 * 0
2. What is your current technology stack? Why use ts?
typescript
is a superset of JavaScript
. It is essentially the addition of JavaScript
optional static type and class-based object-oriented programming to
.
Features of
- Errors can be found and corrected during compilation
- Improve maintainability
- Improve the efficiency of collaborative development
- Supports strong typing, interfaces, generics, modules
3. The execution process of setTimeout (event loop, synchronous, asynchronous)?
event loop
- 1. Execute synchronous code
- 2. The
1
generated inis executed first
- 3. Execute the
1
macro task produced inagain
sync
Simply put: line up. The code has a front and back order and must be executed in order
async
Asynchronous tasks can not block the execution of the following code, but can be performed at the same time, and there will be an asynchronous callback after execution.
Think of a story that explains synchronously and
asynchronously
- Synchronization: You call to the bookstore to borrow a book, the boss asks you to wait when he answers the phone, he looks for the book, you can only wait by the phone
- Asynchronous: You call the bookstore to borrow a book. The boss answers the phone and says that he will call you back when he finds the book, and then hang up. You can move freely during this period of time when you are looking for a book.
4. What is the difference between Promise and async and await? How are async and await implemented?
Understanding of
As the name suggests, Promise
is commitment means, in the performance of the Promise will not change state once again changed, if the state is
fulfilled
execute then
, if the state is rejected
is executed catch
, Promise also supports chained calls. I think the biggest use of Promise is that
solves the callback hell and improves the readability of the code. Commonly used methods are
resolve、reject、then、catch、race、all、allSettled、any、finally
async await
The role of async/await
is that performs asynchronous operations in a synchronous manner. My personal understanding is to use the continuous nesting of
Promise
, coupled with the step control of the generator function, to achieve the effect of performing asynchronous operations in sequence.
Supplement: async function returns a Promise
5. Explain requestAnimationFrame/requestIdleCallback, what is the use of each?
requestAnimationFrame:
- The general interval is
16ms
, because most computers are 60 frames per second, so1000 / 60 ≈ 16ms
- All DOM operations in each frame will be centralized and completed in one redraw or reflow, and the time interval closely follows the refresh rate of the browser
- If there are hidden or invisible elements, it will not be redrawn or reflowed, reducing the memory usage of cpu and gpu
- To cancel use
cancelAnimationFrame
- The general interval is
- requestIdleCallback: My understanding is to find the browser's idle time to execute the incoming callback, which has not been used in the project.
6. React performance optimization?
7. Tell me about your understanding of flex?
elastic layout, set the box of
display: flex
to elastic box, the child elements will automatically become
elastic items, the box has a main axis, the default is horizontal, and there is a cross axis (vertical to the main axis).
Flexbox style:
- flex-direction: defines the main axis direction
- flex-wrap: whether to allow wrapping
- flex-flow: shorthand for flex-direction and flex-wrap
- justify-content: the alignment in the main axis direction
- align-items: the alignment of the cross-axis direction
- align-content: the alignment of multiple axes
Styles for flex items:
- order: defines the arrangement order of the items, the smaller the value, the higher the order, the default is 0
- flex-grow: defines the enlargement ratio of the item, the default is
0
- flex-shrink: defines the shrink ratio of the item, the default is 1
- flex-basis: defines the main axis space occupied by the item before allocating excess space, default auto
- flex: shorthand for flex-grow, flex-shrink, flex-basis
align-self: Allows individual items to set different cross-axis alignments
8. What is reflow and redraw? How to reduce reflow and redraw?
Redraw reflow
- Reflow: When the size and layout change, cause the page to rebuild
- Redraw: When the appearance and style of an element change without affecting the layout, it will be redrawn
- Difference: Reflow must cause redrawing, and redrawing does not necessarily cause reflow
- Browser help: The browser maintains a queue and puts all operations that cause reflow and repainting into this queue. When the queue reaches a certain number or a certain time interval, the browser will clear the queue and perform batch processing.
Avoid redrawing and reflow
- 1. Batch modify DOM or styles
- 2. Use absolute positioning for complex animations to keep them out of the document flow, otherwise there will be frequent reflow of elements or subsequent elements.
3. GPU acceleration: transform, opacity, filters, will-change and other styles
9. How to judge whether an object is an array?
- Object.prototype.toString.call(xxx)
- Array.isArray(xxx)
xxx instaceOf Array
10. How to find the reason why the react page is stuck?
11. Programming question: Implement the flatten method of an object, as follows:
const obj = { a: { b: 1, c: 2, d: { e: 5 } }, b: [1, 3, {a: 2, b: 3}], c: 3 }
The result of flatten(obj){} is returned as follows:
// { // 'a.b': 1, // 'a.c': 2, // 'a.d.e': 5, // 'b[0]': 1, // 'b[1]': 3, // 'b[2].a': 2, // 'b[2].b': 3 // c: 3 // }
problem solving
const isObject = (target) => { return typeof target === 'object' && target !== null } const flatten = (obj) => { if (!isObject) return const res = {} const dfs = (cur, prefix) => { if (isObject(cur)) { if (Array.isArray(cur)) { cur.forEach((item, index) => dfs(item, `${prefix}[${index}]`)) } else { for(let key in cur) { dfs(cur[key], `${prefix}${prefix ? '.' : ''}${key}`) } } } else { res[prefix] = cur } } dfs(obj, '') return res }
two sides
1. Talk about your understanding of web workers
- 1. Start a sub-thread, and perform some big data processing or time-consuming operations in this sub-thread
- 2. Use
postMessage
andonmessage
to realize the communication between the main thread and the child thread - 3. Use
onerror
monitor whether the sub-thread is hung up - 4.
web worker
does not change the fact that JavaScript is single-threaded
2. What are the advantages of service worker compared to strong cache?
The service cache is not used. .
3. Tell me about your understanding of stack overflow?
The common situation occurs when a large number of recursion or
infinite loop, which will cause
stack overflow, because every time the code is executed, a certain space of memory needs to be allocated. The above two cases will make the execution space exceed the maximum limit, and an error will be reported.
4. What is the sticky in position, and what are the others?
- static: default
- relative: relative positioning, positioning relative to itself
- absolute: absolute positioning, positioned relative to the non-static first ancestor element
- fixed: positioning relative to the browser window
- inherit: specifies that the value of the position attribute should be inherited from the parent element
- sticky: ceiling positioning
5. What do any and unknown mean in ts? How to use generics?
- any: If the variable is of type any, all type checks are bypassed and can be used directly
- unknown: If the variable is of unknown type, it can only be used after judging what type it is.
6. What is the use of bind? After multiple binds in a row, what does this point to at the end?
The function of bind
is to change the direction of the function execution, and it will not be executed immediately, but returns a new function, which can call the execution of this function independently (this function cannot be used as a constructor)
After multiple binds in a row, this always points to the first one
7. How to implement the plugin of webpack?
A plugin is a class. There is a apply method in the class. The apply method is called every time it is packaged, and the apply method accepts a parameter object, including a
plugin
method. There are many hook functions in this method, and can be determined Static file generation, modification, etc.
8. Programming questions:
It is now known that a string is composed of positive integers and four operators (+ - /) of addition, subtraction, multiplication and division. For example, there is a string const str = '11+2-3 4+5/2 4+10/5', now you need to wrap the high-priority operation in parentheses, for example, the result is '11+2-( 3 4)+(5/2*4)+(10/5)'. Note that there may be consecutive multiplication and division operations that need to be wrapped together. Please implement this process with javascript
Answers
I compared dishes, and the method I used was improvised. There is no optimization. Let's see:
const checkType = (str) => {
if (['*', '/'].includes(str)) return 'high'
if (['+', '-'].includes(str)) return 'low'
return 'number'
}
const addBrackets = (formula) => {
const strs = formula.split('')
let i = 0, j = 1, high = false, res = []
while(j < strs.length) {
const jType = checkType(strs[j])
if (jType === 'low' && !high) {
i = ++j
j++
}else if (jType === 'low' && high) {
res.push(j++)
i = j++
high = false
}else if (jType === 'high') {
j++
!high && res.push(i)
high = true
}else {
j++
}
}
if (high) res.push(strs.length)
let add = 0
for(let i = 0; i < res.length; i++) {
const index = res[i]
strs.splice(index + add, 0, add % 2 ? ')' : '(')
add++
}
return strs.join('')
}
Three sides
1. Handwritten: Use TypeScript to implement a get function to get its property value
const data = { name: 'tom', age: 18, address: 'xxx' }
answer:
const get = <T extends object, K extends keyof T>(obj: T, key: K): T[K] => {
return obj[key]
}
2. What is the difference between any and unknown in ts?
- any: If the variable is of type any, all type checks are bypassed and can be used directly
unknown: If the variable is of unknown type, it can only be used after judging what type it is.
3. Have you used keyof in ts?
Aggregate all keys of an interface into a union type, which can be used to limit incoming keys, such as:
interface Target { name: string, age: number } const fn = (obj: Target, key: keyof Target) => {} const obj: Target = { name: 'sunshine', age: 18 } fn(obj, name) // 成功 fn(obj, age) // 成功 fn(obj, height) // 报错
4. What is the difference between for in/for of?
- for in: traverse the key of the object or the index of the array
for of: iterates over the values of iterable objects, such as arrays, Sets
5. Promise value penetration
If then or catch does not pass in a function, value penetration will occur. The principle is that if the internal detection of Promise is a non-function, the last result will be packaged into a function that returns Promise to achieve the penetration effect.
For example:
Promise.resolve('foo')
.then(Promise.resolve('bar'))
.then(function(result){
console.log(result) // foo
})
But if you pass in a function:
Promise.resolve('foo')
.then(() => Promise.resolve('bar'))
.then(function(result){
console.log(result) // bar
})
Epilogue
Because I am too bad at React, I dare not answer questions about React
I'm Lin Sanxin, an enthusiastic front-end rookie programmer. If you are motivated, like the front-end, and want to learn the front-end, then we can make friends and fish together haha, touch the fish group, add me, please note [Si No]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。