In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces to you 5 examples of how to improve your JavaScript coding level, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Although 2020 today, a variety of front-end frameworks, tools, and these frameworks and tools also help us solve a lot of troublesome problems ahead of time, but tools are always tools, solid basic skills are the core, now let's improve our native JS coding level through a few actual code snippets.
Determine the data type
First of all, let's ask a question: can typeof correctly judge the type?
The answer is: no, because for historical reasons, typeof null equals object when judging the original type. And for objects, except for functions, they are converted to object. Examples are as follows:
Typeof 1; / / 'number'
Typeof "1"; / / 'string'
Typeof null; / /
Typeof []; / / 'object'
Typeof {}; / / 'object'
Typeof window.alert; / / 'function'
Let's ask another question: can instanceof correctly judge the type?
The answer is: no, although instanceof is judged by the prototype chain, for objects, Array is also converted to Object, and there is no distinction between the basic types string and boolean. For example:
Function Func () {}
Const func = new Func ()
Console.log (func instanceof Func); / / true
Const obj = {}
Const arr = []
Obj instanceof Object; / / true
Arr instanceof Object; / / true
Arr instanceof Array; / / true
Const str = "abc"
Const str2 = new String ("abc")
Str instanceof String; / / false
Str2 instanceof String; / / true
So what should we do?
At this point we can use: Object.prototype.toString.call ()
So why?
Because each object has a toString () method, this method is automatically called when you want to represent the object as a text value or refer to the object as an expected string. By default, every object that derives from Object inherits the toString () method. If this method is not overridden in the custom object, toString () returns [Object type], where type is the object type. So there are the following examples:
Object.prototype.toString.call (new Date ()); / / [object Date]
Object.prototype.toString.call ("1"); / / [object String]
Object.prototype.toString.call (1); / / [object Numer]
Object.prototype.toString.call (undefined); / / [object Undefined]
Object.prototype.toString.call (null); / / [object Null]
Therefore, combining the above knowledge points, we can encapsulate the following general type judgment methods:
Var type = function (data) {
Var toString = Object.prototype.toString
Var dataType = data instanceof Element
? 'element' / / to unify the output of DOM node types
: toString
.call (data)
.replace (/\ [object\ s (. +)\] /,'$1')
.toLowerCase ()
Return dataType
}
The method of use is as follows:
Type ("a"); / / string
Type (1); / / number
Type (window); / / window
Type (document.querySelector ("H2")); / / element generic array / class array object encapsulation
If we use ES5/ES6+ 's array API, we can easily loop through the array, but what if we want to loop through an array object?
For example, NodeList. A direct loop will report an error:
Document.querySelectorAll ("div") .map (e = > e); / / Uncaught TypeError: document.querySelectorAll (...) .map is not a function
Of course, we can use the extension operator:
[... document.querySelectorAll ("div")] .map (e = > e)
What if we don't use the extension operator?
Then we can take advantage of the features of call to insert the elements in NodeList into the array one by one, as shown in the following example:
Var listMap = function (array, type, fn) {
Return! fn? Array: Array.prototype [type] ["call"] (array, fn);}
The method of use is as follows:
Var divs = document.querySelectorAll ("div")
ListMap (divs, "forEach", function (e) {
Console.log (e)
}); get the offset of the dom element node
If you have used jQuery's children's shoes, you will never forget the powerful function of $('). Offset (), this api can easily get the offset of the element, so how can we achieve it if we don't use jQuery?
Let's first look at the example:
Var getOffset = function (el) {
Var scrollTop =
El.getBoundingClientRect () .top +
Document.body.scrollTop +
Document.documentElement.scrollTop
Var scrollLeft =
El.getBoundingClientRect () .left +
Document.body.scrollLeft +
Document.documentElement.scrollLeft
Return {
Top: scrollTop
Left: scrollLeft
}
}
First of all, let's look at the getBoundingClientRect () method.
The getBoundingClientRect () method returns the size of the element and its position relative to the viewport. The return value is a DOMRect object, which is the collection of CSS borders associated with the element.
Then there is document.body.scrollTop and document.documentElement.scrollTop, which are the same function, but one is always 0 in different browsers, so the above compatibility processing has been done. So when we do the drag and drop function, we can rely on the above properties.
The method of use is as follows:
Var el = document.querySelector (".moveBox")
GetOffset (el); / / {top: xxx, left: xxx}
We can see the joystick effect above, and here we use offset () to determine the position. The specific implementation code can be found in: https://codepen.io/krischan77/pen/zYxPNPy
Fade special effects / / Fade in
Var fadeIn = function (el) {
El.style.opacity = 0
Var last = + new Date ()
Var tick = function () {
El.style.opacity = + el.style.opacity + (new Date ()-last) / 400
Last = + new Date ()
If (+ el.style.opacity)
< 1) { requestAnimationFrame(tick)) } } tick() } // Fade out var fadeOut = function (el) { el.style.opacity = 1 var last = +new Date() var tick = function() { el.style.opacity = +el.style.opacity - (new Date() - last) / 400 last = +new Date() if (+el.style.opacity >0) {
RequestAnimationFrame (tick)
}
}
Tick ()
}
The above is the specific implementation of the fade-in and fade-out effect. Here, the opacity is modified recursively by using requestAnimationFrame.
In fact, we need to mention a concept here, that is, time slicing.
This is a very important concept. For example, the Fiber core implementation of React is time slicing. It splits a long task into a queue of small tasks, and then executes them one by one.
RequestAnimationFrame is such an API, which can decide the execution time of the callback function according to the system, that is, update the animation frame before the next redraw. Because there is such a mechanism, it can prevent frame loss.
Use the concept of queue for data operation
Queue (queue) is a linear table of first-in, first-out (FIFO, First-In-First-Out). In specific applications, it is usually implemented by linked lists or arrays. Queues only allow inserts at the back end (called rear) and deletions at the front end (called front).
Although many people feel that understanding data structures does not have much effect on the front end, if we understand some basic concepts, can we spread our thinking more when coding? Let's look at the following two examples:
Gets the coordinates of the node under the parent node.
If we want to manipulate the native DOM, we can't get around the function of getting the subscript of the node at the parent node, so how do we do that?
Of course, using our loop, we iterate through the collection of child elements until the subscript is determined, and the code is as follows:
Var index = function (el) {
If (! el) {
Return-1
}
Var I = 0
While ((el = el.previousElementSibling)) {
ITunes +
}
Return i
}; clear child nodes
If we want to empty the children of a DOM node, we have the following methods:
Var empty = function (el) {
While (el.firstChild) {
El.removeChild (el.firstChild)
}
}
The above just provides an idea, but el [XSS _ clean] =''would be more concise.
Using reduce for data optimization array deduplication
Yes, it's another old problem, array deduplication, but this time we remove not just a single piece of data, but a collection of objects with the same key value. For example, in the following example, we have the following data:
Powerful reduce data de-duplication
First of all, let's take a look at an old question. Let's assume that there is such an object:
Const data = [
{
Name: "Kris", age: "24"
}
{
Name: "Andy", age: "25"
}
{
Name: "Kitty", age: "25"
}
{
Name: "Andy", age: "25"
}
{
Name: "Kitty", age: "25"
}
{
Name: "Andy", age: "25"
}
{
Name: "Kitty", age: "25"
}]
Now we are going to add the duplicate objects in name. At this time, we can use reduce. The example is as follows:
Const dataReducer = (prev, cur, idx) = > {
Let obj = {}
Const {name} = cur
Obj [name] = cur
Return {
... prev
... obj
}
}
Const reducedData = data.reduce (dataReducer, {})
Let newData = Object.values (reducedData); batch generate object elements
In the actual business of fish head, there is an operation that needs to operate on objects similar to the following:
{
A1: 'data'
A2: 'data'
...
An: 'data'
}
Lazy fish like me can't write by hand one by one, so there are the following ways
Const createList = (item, idx) = > {
Let obj = {}
Obj [`a$ {idx} `] = "data"
Return obj
}
Const listReducer = (acc, cur) = > (! acc? {... cur}: {... cur,... acc})
Const obj = Array.from (new Array (20), createList). Reduce (listReducer); this is the end of 5 examples of how to improve your JavaScript coding level. I hope the above can be helpful and learn more. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.