The problem the forerunner
- The Difference between Progressive Enhancement and Graceful Degradation
-
transform
What are the properties? “CSS” - What are the common layout units of the CSS? “CSS”
- How do array-like objects become arrays? 【 JS Basics 】
- What native methods do arrays have? 【 JS Basics 】
- What is the difference between UTF-8 and UTF-16? 【 JS Basics 】
- Can a child component directly modify the parent component’s data? 【 Vue 】
- How does Vue collect dependencies? 【 Vue 】
- Implement array out of order output
- Implement array flattening
- Code output results (Promise related)
- Hierarchical Traversal of n-tree
Knowledge comb
The difference between progressive enhancement and graceful degradation
Progressive Enhancement is a design concept that, at its core, provides basic content and functionality to as many users as possible, while further providing the best experience for modern browser users, running all the required code. The key is to ensure that basic features work in most browsers, and then worry about the user experience of modern browsers.
Feature detection is typically used to determine if the browser can handle advanced content, while polyfill is typically used to build missing functionality using JavaScript.
Graceful degradation is a design concept with progressive enhancement boxes. At its core, it tries to build a modern website/application that runs in the latest browsers, while still providing the necessary content and functionality as a degraded experience in older browsers. That means focusing on the modern browser experience and then thinking about the experience of older browsers.
Similarly, Polyfill can be used to build missing functionality using JavaScript, but should provide acceptable alternatives to functionality such as style and layout whenever possible, such as CSS cascading or HTML fallback behavior. Some good examples can be found in dealing with common HTML and CSS problems.
transform
What are the properties?
The CSS** Transform ** property allows you to rotate, scale, tilt, or pan a given element. This is done by modifying the coordinate space of the CSS visual formatting model. Unlike normal positioning, Transform uses the GPU for hardware acceleration, is also a property specifically used for animation, and does not trigger document backflow.
Transform One or more CSS transform functions that are controlled by transform functions to be applied. The transformation functions are multiplied from left to right, which means that the composition transformations are efficiently applied from right to left.
Commonly used exchange functions are:
matrix
: matrix function. CSS functionmatrix()
Use six specified values to specify a uniform two dimensional (2D) transformation matrix. The constant values in this rectangle are not passed as arguments; the other arguments are described in the order of the main columns.matrix(a, b, c, d, tx, ty)
是matrix3d(a, b, 0, 0, c, d, 0, 0, 0, 0, 1, 0, tx, ty, 0, 1)
The shorthandmatrix3d
Function: CSSmatrix3d()
A three dimensional (3D) transformation is described by a 4 × 4 homogeneous matrix. All 16 parameters are described in the order of the main column.rotate
: Rotates an element around a fixed point without deforming it (e.gtransform-origin
If it is negative, it is counterclockwise.rotateX
: defines a way to rotate an element on the x-coordinate without deforming it, equivalent to rotating an element around the X-axis.rotateY
: defines a way to rotate an element on the Y-axis without deforming it.rotateZ
: defines a way to rotate an element in the Z coordinate without deforming it, equivalent to rotating an element around the Z axis.rotate3D
: combination of the above four functions: rotate3D(x, y, z, a).scale
: zoom.scale(sx, sy)
: Scales with respect to the x and y axes.scale3D
scaleX
scaleY
scaleZ
skew
: Tensile Angle.scale(ax, ay)
: Rotates relative to the x and y axesskewX
skewY
translate
: translation.translate(tx, ty)
translate3D
translateX
translateY
translateZ
Reference:
- transform – MDN
- transform-function – MDN
What are the common layout units of the CSS?
- Pixel (PX) : The smallest unit of image cutting, usually CSS pixel and physical pixel. CSS pixel: An abstract unit for web developers to use in CSS; Physical pixels: The physical pixels of any device are fixed, depending only on the hardware density of the device.
- Percentage (%)
- Length ratio:
em
andrem
.em
Is the ratio of parent length to parent element,rem
Is the ratio of length to the root element. - Percentage of window width and height:
vw
andvh
That is, the ratio of window width to height multiplied by 100.
How do array-like objects become arrays?
An object with a length attribute and several index attributes can be called an array-like object, which is similar to an array but cannot call array methods. Common array-like objects include arguments and the return results of DOM methods, and a function that can also be considered an array-like object because it has the length property value, representing the number of arguments that can be accepted.
-
Using the slice function:
Array.prototype.slice.call(arrayLike); Copy the code
-
Use the splice function:
Array.prototype.splice.call(arrayLike, 0); Copy the code
-
Using the concate function:
Array.prototype.concat.apply([], arrayLike); Copy the code
-
Use the array. from method to convert:
Array.from(arrayLike); Copy the code
What native methods do arrays have?
const arr = [1.2.3];
// Array to string
arr.toString();
arr.toLocaleString();
arr.join(', ');
// Add and delete elements of array
arr.push(); // add a tail
arr.pop(); // delete the tail
arr.unshift(); // Add header
arr.shift(); // Delete the header
arr.concat([1.3.5]) // Array concatenation
arr.slice(0.3); // Array subsequence interception [start, end]
arr.splice(0.1.2.3); // remove elements and insert elements at their removed locations [start, deleteCount,...inserts]
// Array traversal
arr.forEach(n= > console.log(n));
arr.includes(1);
arr.indexOf(1);
arr.lastIndexOf(1);
arr.filter(n= > n % 2= =0);
arr.map(n= > n * 2)
/ / other
arr.every(n= > n % 2= =0); // Check whether all elements of the array match the specified condition
arr.some(n= > n > 0); // Is used to check whether the elements in the array meet the specified condition
// Receives a function as an accumulator, where each value in the array (from left to right) is reduced to a single value.
arr.reduce((total, n) = > {
return total + n
})
// The function of reduceRight() is the same as that of reduce(), except that reduceRight() adds the items in the array forward from the end of the array.
Copy the code
What is the difference between Unicode and character encodings such as UTF-8 and UTF-16?
Before we get to Unicode, we need to understand ASCII: THE ASCII Code (American Standard Code for Information Interchange) is called the American Standard Code for Information Interchange.
- It is a computer coding system based on the Latin alphabet.
- It defines a dictionary for representing common characters.
- It contains “A-z “(case and case), the data “0-9”, and some common symbols.
- Designed specifically for English, it has 128 codes and is useless for other languages
ASCII is limited in the number of encodings it can represent. To represent the encodings of other languages, it is necessary to use Unicode, which is a superset of ASCII.
Unicode Translation Format, also known as Unicode, universal code, single code. Unicode was created to overcome the limitations of traditional character encoding schemes. It provides a unified and unique binary encoding for each character in each language to meet the requirements of cross-language and cross-platform text conversion and processing.
Unicode can be implemented (or encoded) in many ways, the most common being UTF-8, UTF-16, UTF-32, and USC-2.
Utf-8 is the most widely used Unicode encoding. It is a variable-length encoding ranging from 1 to 4 bytes and is fully compatible with the 128 characters of ASCII.
Utf-16 is also an encoding form of the Unicode coset that maps abstract code points of the Unicode character set to sequences of 16-bit long integers (known as codes) for data storage or transmission.
Using UTF-8 saves a lot more space than USING UTF-16 if the character content is entirely In English or if English is mixed with other characters, but Most of the characters are In English. However, if the content of characters is all Chinese characters, such as similar characters or mixed characters with the majority of Chinese characters, then UTF-16 is dominant and can save a lot of space.
Can a child component directly change the parent component’s data?
A child component cannot directly alter the parent component’s data. This is done primarily to maintain one-way data flow between parent and child components. Every time the parent component is updated, all prop in the child component will be refreshed to the latest value. If the child modifies the data passed by the parent, Vue will issue a warning in the browser console.
Vue advocates one-way data flow, where updates to the parent props flow to the child components, but not the other way around. This is to prevent unexpected changes in the state of the parent component, making the application data flow difficult to understand, resulting in data flow chaos. Debugging can be costly when applications are complex if one-way data flows are broken.
If the parent component needs to modify the parent component’s data, the parent component needs to expose the interface to the parent component, that is, provide the trigger event: send a custom event through $emit, and the parent component will modify it after receiving the custom event.
How does Vue collect dependencies?
When each component of the Vue is initialized, the component’s data is initialized to change the normal object into a responsive object, and the dependent collection logic is used in this process:
function defieneReactive (obj, key, val){
const dep = newDep(); .Object.defineProperty(obj, key, {
...
get: function reactiveGetter () {
if(Dep.target){ dep.depend(); . }returnval } ... })}Copy the code
Vue instantiates an object as follows:
- use
Object.defineProperty
orProxy
implementationThe data was hijacked. That is, intercepting changes in data for responsive updates. - During data hijacking, dependencies are constantly collected and data is passed through
Observer
willThe observerAdded to theDep
In the object - Then the event listening mechanism passes through
Watcher
Object will beThe subscriberAdded to theDep
In the object. - In this way,
Dep
There is a dependency between the observer and the subscriber. When the data changes, the data is hijacked, and the observer detects the change and notifies itDep
To react,Dep
After sending a message to all subscribers, the subscribers will update the view, thus achieving the effect of data responsive update of the view.
Reference:
- Vue source code interpretation of Dep,Observer and Watcher
Implement array out of order output
Output out of order is to generate a random index, and then fetch, and so on, until the array is finished.
- Take the first element of the array, generate a random index value, and swap the first element with the corresponding element of the index.
- The second time we take the second element of the data array, randomly generate an index value other than that of index 1, and swap the second element with the corresponding element of that index value
- Follow the above rules until the traversal is complete
var arr = [1.2.3.4.5.6.7.8.9.10];
for (var i = 0; i < arr.length; i++) {
const randomIndex = Math.round(Math.random() * (arr.length - 1 - i)) + i;
[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
}
console.log(arr)
Copy the code
The ** math.random ()** function returns a floating point pseudo-random number in the range from 0 to less than 1, that is, up from 0 (including 0) but not including 1 (excluding 1), which you can then scale to the desired range.
Implement array flattening
Flattening means expanding the array inside an array into a one-level array, for example [1,2, [3, 4], 5] flattening becomes: [1,2, 3, 4, 5].
The idea is very simple, just go through the array, flatten it when you see an array, and then insert the current position of the array.
/ * * *@param {any[]} arr
* @returns any[]
*/
function flatten(arr) {
const res = [];
arr.forEach(item= > {
if(Array.isArray(item)) { res.push(... flatten(item)); }else{ res.push(item); }});return res;
}
Copy the code
Code output results (Promise related)
Code snippet:
async function async1() {
console.log("async1 start");
await async2();
console.log("async1 end");
}
async function async2() {
console.log("async2");
}
async1();
console.log('start')
Copy the code
A. await B. await C. await D. await
async1 start
async2
start
async1 end
Copy the code
Code snippet:
async function async1() {
console.log("async1 start");
await async2();
console.log("async1 end");
setTimeout(() = > {
console.log('timer1')},0)}async function async2() {
setTimeout(() = > {
console.log('timer2')},0)
console.log("async2");
}
async1();
setTimeout(() = > {
console.log('timer3')},0)
console.log("start")
Copy the code
(2) {” await “=” await “; (3) {” await “=” await “;
-
Perform async1 ()
console.log("async1 start"); // Prints async1 start async2(); // console.log(timer2) enters the asynchronous macro task queue; Print async2; The code then moves into asynchronous microtasks Copy the code
-
Console. log(‘timer3’) enters the asynchronous macro task queue
-
Run console.log(“start”) to print start
-
The macro task is finished and the micro task in the queue is executed:
// The microtask in async1() starts executing console.log("async1 end"); // Prints async1 end setTimeout(() = > { console.log('timer1') // Enter the asynchronous macro task queue }, 0) Copy the code
-
When the microtask is completed, the macro task in the queue is executed:
console.log(timer2); / / print time2 console.log(time3); / / print time3 Copy the code
-
When the macro task is executed, the microtask in the queue is executed. If no microtask is executed, the macro task in the queue is executed again:
console.log('timer1') / / print time1 Copy the code
-
Code execution complete
Comb through the print above:
async1 start
async2
start
async1 end
timer2
timer3
timer1
Copy the code
N – tree sequence traversal
Given an n-tree, return a sequential traversal of its node values. (that is, from left to right, layer by layer). The serialized input to the tree is traversed in order, with each set of child nodes specified bynullValue separation (see example). Enter: root = [1.null.3.2.4.null.5.6] Output: [[1], [3.2.4], [5.6]]
/** * // Definition for a Node. * function Node(val,children) { * this.val = val; * this.children = children; *}; * /
Copy the code
In this case, logarithms are required to perform hierarchical traversal, also known as breadth-first traversal (BFS) of numbers. Breadth-first traversal is based on queues:
var levelOrder = function(root) {
const result = [];
if (root == null) return result;
const queue = [];
queue.push(root);
while (queue.length) {
const level = [];
const len = queue.length;
for (let i = 0; i < len; i++) {
constnode = queue.shift(); level.push(node.val); queue.push(... node.children); } result.push(level); }return result;
};
Copy the code