preface

Recently, I just joined Didi. When I moved from Chengdu to Beijing, I changed a company and also a city. I have a lot of feelings. I was lucky enough to see the complete system and benefits of a big company, which really opened my horizon. Since I just joined a new company, I am still familiar with various businesses and have few development tasks. I’m a busy person, but I haven’t been working on a lot of projects lately, and I want to write a little bit. So, I’d like to share some apis that are useful for actual development.

1, the Element. The classList

Element.classList, a read-only property, returns a real-time DOMTokenList collection of an Element’s class attributes.

In the previous era of using jQuery, it provided addClass and removeClass and other DOM className manipulation methods like us. However, due to the separation of A-V-R front-end framework,jQuery is gradually abandoned by The Times. Therefore, We can use the native methods provided by DOM to operate on a node’s className (if the user implements the className operation himself, and if some business boundaries are missing, especially for developers who are new to the front-end domain).

var app = document.getElementById('app');
// Add the style name to the DOM node
app.className.add('mobile');
app.className.add('mobile-iphone');
// Remove the style name from the DOM node
app.className.remove('mobile-android');
// Toggle the DOM node style name, if not add, remove if there is
app.className.toggle('pc');
Copy the code

For more details on the API, consult the documentation for DOMTokenList

compatibility

2, URLSearchParams

Are you still getting query strings like this?

function queryString() {
    var search = decodeURIComponent(window.location.search);
    search = search.replace(/ ^ \? /.' ');
    var patterns = search.split('&');
    var dist = {};
    patterns.forEach(x= > {
        var group = x.split('=');
        var key = group[0];
        var value = group[1];
        dist[key] = value;
    });
    return dist
}
Copy the code

If you’re still writing this, you’re out. HTML5 has introduced a new API called URLSearchParams

The URLSearchParams interface defines some useful methods for handling query strings for urls.

When using URLSearchParams, we need to pass in the initialized query string. That is:

var queryString = window.location.search;
var q = new URLSearchParams(queryString);
// Add a new key-value pair
q.append('gender'.1);
// Delete a key-value pair
q.delete('name');
// Check whether there are key-value pairs
q.has('name');
// Get the value of a key
q.get('gender');
/ /... For more apis, see MDN
// Get the final query string
q.toString();
Copy the code

compatibility

URLSearchParams compatibility is relatively poor, if there is no compatible IE requirements of partners, you can rest assured to use it.

3, MutationObserver

Creates and returns a new MutationObserver that is called when the specified DOM changes.

// The target node that needs to be observed to change
const targetNode = document.querySelector('#app');
// Observe the changed configuration
const config = { attributes: true.childList: true.subtree: true };
// Create the observe incoming callback function
const observer = new MutationObserver(function(mutationsList, observer) {
    for(let mutation of mutationsList) {
        if (mutation.type === 'childList') {
            console.log('Node change');
        }
        else if (mutation.type === 'attributes') {
            console.log('Attribute change'); }}});// Start observing the target node
observer.observe(targetNode, config);
// Stop observing the target node
observer.disconnect();
Copy the code

This API is useful when we need to listen for DOM node changes. One such change in the MutationObserver is our well-known microtask. In addition, MutationObserver can trigger very frequently, so when using it, be careful to limit cooling with throttling or anti-shaking.

compatibility

Overall, the Compatibility of MutationObserver is good.

4, Element. GetBoundClientRect ()

Element. GetBoundingClientRect () method returns the Element size and its position relative to the viewport. For a standard box model, the size of the element is equal to the sum of width/height + padding + border-width. If box-sizing: border-box, the element size is equal to width/height.

The return value of this method is a DOMRect object, which is the smallest rectangle containing the entire element and has the left, top, right, bottom, x, y, width, and height read-only attributes in pixels describing the entire border. Properties other than width and height are evaluated relative to the top left corner of the view window.

One of the easiest ways to determine if an element is visible is to use getBoundClient. When the left,top,right, and bottom of a DOMRect object are all greater than 0 at the same time, we know that the element is in the viewable area. Another advantage is that this method is more concise than the old API, such as access to the offsetLeft and offsetTop, offsetHeight, offsetWidth to use more complex, as this method to directly.

5, Array. The from

In real development, we often encounter array-like objects. DOMTokenList as stated above, the arguments, NodeList, etc., and we used to use an array of standard iteration method is superior and convenient, we more hope for class array object in into array traversal is more convenient. So in some old, classic books you might often see code like this:

Array.prototype.slice.call(arrayLike);
/ / or
[].slice.call(arrayLike);
Copy the code

The array.from () method creates a new, shallow-copy Array instance from an array-like or iterable.

The new API simplifies writing and allows it to iterate over iterators.

Array.from(arguments);// Convert arguments to a real array.
Array.from(map.values())// If map is an instance of map, map.values() returns an Iterator;
Copy the code

Note: The extension operator can achieve the same effect as array. from, which is very embarrassing and not surprising. The above code can be rewritten as:

[...arguments];
[...map.values()];
Copy the code

Object traversal, array traversal

6.1 Object Traversal

There are the following common methods: Object.keys(), object.values (), object.entries (). All three methods return an attribute whose enumerable property is true for the current Object (that is, no property on the original Object) (Object. DefineProprty (Target, prop, {enumerable: Keys () returns all keys, values() returns all values, and Entries () returns an array of keys and values. Therefore:

Var stocks = {'SH002230': 'SH600036': 'China Merchants Bank ', 'SH600519':' Kweichow Moutai ',} var codes = Object.keys(stocks); //['SH002230', 'SH600036', 'SH600519']; var values = Object.values(stocks); //[' IFLYtek ', 'China Merchants Bank ',' Guizhou Maotai ']; var mapping = Object.entries(stocks); / / [[' SH002230 ', 'hkust xunfei], [' SH600036', 'China merchants bank], [' SH600519', 'guizhou maotai]] mapping. The forEach (([prop, Value]) => {// Use destruct assignment here to help our code to be more concise and semantic. console.log(prop, value); });Copy the code

6.2 Array traversal

Array traversal has the following common methods:.foreach (),.map(); .some(); .every(); .filter(); .reduce(); .reduceRight();

What is the difference between forEach and Map? ForEach traversal, map projection operation, returns a new array. If you don’t accept the array.prototype. map return structure, forEach and map are almost the same in principle, but for the sake of semantics, I would recommend not mixing forEach, map, filter, etc., if you want to use a function, It is better to use the corresponding semantic traversal method.

But there’s a new pit, for object arrays. If you modify the source object while traversing, then you have already modified the source array object with map or forEach. Therefore, to prevent unexpected operations, I recommend that you do not manipulate the source object while traversing the array of objects.

var arr = [{}, {}, {}, {}];
arr.forEach(item= > {
    // Since the object is passed by reference, we modify the object, thus changing the original array
    item.ddd = 'demo';
    console.log(item);
});
Copy the code

All array traversal methods skip empty elements. Such as:

var array = [1.undefined.5.8.10,];
// Arrays allow trailing commas
array.length / / 8
array.forEach(item= > {
    console.log(item);
})
// Print 1, undefined, 5, 8, 10
Copy the code

Because regular forEach is not interruptible, but we do sometimes need to interrupt traversal, we can consider using some or every methods instead.

array.forEach(item= > {
    if(item > 10) {
        // Cannot interrupt the end traversal
        return; }}); array.every(item= > {
    if(item > 10) {
        // Force the current traversal to end
        return false; }})Copy the code

The reduce method is the only one THAT I can’t always remember what parameters I need to pass, and is commonly used for operations such as sums. This doesn’t mean you have to use this method, but it does make your code simpler and easier to understand.

Array.prototype.reduce((accumulator, currentValue, index? , array?) = > {
    // Do some operations}, initValue?) ;Copy the code

InitialValue is optional and, if passed, will be the value initially summarized when the callback function is first called. If no initial value is provided, the first element in the array is used. An error is reported when the array is empty and initValue is not passed. ReduceRight and Reduce are similar and will not be described here.

7, FormData

FormData is certainly a common API for modern Web front-end programmers, and THE reason I want to mention it is to highlight its append method. First look at the explanation given by MDN:

The FormData interface provides a way to construct key/value pairs that represent FormData and can easily send the data through the xmlhttprequest.send () method, both of which are fairly straightforward. If the sent encoding type is set to “multipart/form-data”, it will use the same format as the form. If you want to build a simple GET request with query parameters in the form of <form>, you can pass it directly to URLSearchParams.

Most of the modern Web front-end is based on the separation of the front and back end development model, we no longer need to use the form tag to pass data to the background, and whenever we use file upload, we must use this API. Common usage methods are as follows:

var formData = new FormData();
// Suppose there are file1,file2 objects
formData.append('file',file1);
formData.append('timestamp'.new Date());
// File2 does not overwrite the file1 object
formData.append('file', file2);
Copy the code

Append is a very important point in the definition of MDN:

Formdata.append () adds a new attribute value to FormData. The existing attribute value of FormData does not overwrite the original value, but adds a new value. If the attribute value does not exist, it adds a new attribute value.

I originally did not know is not covered, but because of when I was in college to participate in the later stage of development, receive upload file data in the background, the background of receiving is an array, where the same array keys will occur, sparked my thinking, last year due to solve a bug, found the append method of this feature, Then it dawned on me.

conclusion

The above are some of the more practical APIS I have summarized in the development of the past few years, and there may be more friends who feel quite good API, welcome to add oh.

Due to the limited level of the author, it is inevitable that there will be mistakes in the writing process. If there are any mistakes, please correct them. Please contact the author at [email protected], your opinions will help me make better progress.