deconstruction

Deconstruct the concept of assignment

Destruct assignment syntax is a Javascript expression. By deconstructing assignment, you can take a property/value from an object/array and assign it to another variable

Basic use of array deconstruction

Let’s start with the code:

const [ a, b, c, { name }, d = 4 ] = [1.2.3, { name: 'james' }]
console.log(a) / / 1
console.log(b) / / 2
console.log(c) / / 3
console.log(name) // james
console.log(d) / / 4
Copy the code

If we’re deconstructing an array, we need to write an array of the same form that we’re deconstructing to get the data. {name: ‘James’}; So we’re going to write an array, and we’re going to put a variable in there to connect to the data in that array. And we can set a default value when we receive it. For example D, there are only four numbers on the right, so there is no way to make d worthwhile, so we print out 4

Basic use of object deconstruction

const { age: myAge, name } = { name: 'bob'.age: 12 }
console.log(name) // bob
console.log(myAge) / / 12
console.log(age) // age is not defined
Copy the code

To deconstruct an object, we also write an object form to wrap the variable we want to receive. Object destructuring, unlike arrays, is not done in order, but is done according to the key of the object, and if you do not want to use the key of the object as the variable to receive, you can use the age: myAge method to define your own variable name.

Switching variable

In the past, if we wanted to swap the values of two variables, we had to introduce a third variable to swap the values. However, after ES6, we can use the destruct assignment feature to solve this problem

let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); / / 2
console.log(b); / / 1
Copy the code

Omit the assignment

let name = [1.2.3.4.5.6]
let [,,,,,last] = name
console.log(last) / / 6
Copy the code

If you only need to deconstruct one value, if you don’t need to deconstruct the other value, you can just write one value, and then find the order in which you want to deconstruct, and then write the variables.

The For of deconstruction

const info = [
    { name: 'bob'.parent: { name: 'james'}}, {name: 'nancy'.parent: { name: 'jack'}}]for (let { name: n, parent: { name: pName }} of info ) {
    console.log(n, pName)
}
Copy the code

If we have an array of objects, and we want to deconstruct the name of the data and the name of the parent object, we can do the same thing with the object isomorphism, write the name, and then we can write a new abbreviation for the NME.

Template string

describe

Template strings use backquotes (‘ ‘) instead of double and single quotes in normal strings. Template strings can contain placeholders for specific syntax (‘ ${expression} ‘). Placeholders in the expression with the surrounding text will pass to a default function, this function is responsible for all the parts together, if a template string begins by expression, then the string is called template string with labels, the expression is often a function, it will be called after the template string handling, before the output the final result, You can use this function to manipulate template strings. When using a backquote (‘) inside a template string, you need to precede it with an escape character (\).

This is how MDN describes a template string. Here is an example:

const name = 'james'
const age = 25
const tpl = 'My name is${name}This year, I${age}Years old. `
Copy the code

meaning

In the past, when we didn’t have a template string, we had a lot of trouble when we had to concatenate variables with strings

const name = 'james'
const age = 25
const tpl = 'My name is' + name + ', I'm this year ' + age + 'years old.
// If we need to add a newline
const line = 'line1\nline2\n'
/ / or
const otherLine = 'line1 \
line2 \
line3 \
'
Copy the code

‘\n’ is not very intuitive, and if you use \ at the end of the line, you will have problems with the compressed code. After ES6, you will have problems with template strings. It is intuitive and concise, and requires no extra symbols to show line breaks.

Usage scenarios

In addition to simple concatenation string concatenation, we usually use it to write some DOM structure, such as a json data passed to us in the background, and we need to render the JSON data into an HTML list

const json = [{name: 'bob'}, {name: 'james'}, {name: 'nancy'}]
const ul = `<ul>${json.map((user, index) => { return `<li>${index + 1}. ${user.name}</li>` })}`
console.log(ul) // <ul><li>1. bob</li>,<li>2. james</li>,<li>3. nancy</li>
</ul>`
Copy the code

A tagged template string

let toUppercase = function (strings, ... values) {
   let str = ' '
   for (let i = 0; i < values.length; i++) {
     str += strings[i] + values[i].toUpperCase()
   }
   return str
}
let name = 'bob'
toUppercaseI call `${name}` / / my name is BOB
Copy the code

Tagging a template string is equivalent to writing a function and then doing something to the string inside the function. Returns a new string. So, for example, this toUppercase I wrote here. You can capitalize the variables that you write in.

Implement a simple template string

function tplStr(str) {
    let newStr = str.replace(/\$\{([^\}]+)\}/g.function (match, values) {
          return eval(values)
    })
    return newStr
}
const name = 'bob'
const str = 'hello ${name}'
let newStr = tplStr(str) // "hello bob"
Copy the code

To write a simple template string, write the replace method, find the XXX in ${XXX}, and then use eval to find the value, replacing ${XXX}.

conclusion

Today we reviewed the basic operations of array destructuring and object destructuring, and how data can be exchanged using destructuring, how variables can be renamed, how defaults can be set, how assignments can be omitted if written, and so on. Then we reviewed a template string, talked about its simple use, how to use it, how to use the more advanced template tags, and finally implemented a simple template string method ourselves. All right, that’s all for today. See you next time