This time I will show you how to use ES6 templatesStrings, what are the precautions when using ES6 template strings, the following is a practical case, let's take a look.
1. Previously we could also use JavaScript to output a template string, usually as follows:
$("#result").append( "He is <b>"+person.name+"</b>"+"and we wish to know his"+person.age+".That is all" );
But we can see: Such a traditional approach requires the use A lot of "" (double quotes) and splicing can get the template we need. But this is very inconvenient.
So ES6 provides template strings, marked with ` (backtick), and variables enclosed with ${}. The above example can be written as follows using a template string:
$("#result").append( `He is <b>${person.name}</b>and we wish to know his${person.age}.that is all` );
This approach is much simpler, and we no longer need to use a large number of "" and to splice strings and variables.
2. Of course, variables can be introduced into the template string, and it is also possible not to use variables. As shown below:
` I am a man.`
` No matter what you do,
I trust you.`
3. We can also define the variable first, and then embed the variable in the template string:
var name="zzw"; ` ${name},no matter what you do, I trust you.`
4. Obviously, since the backtick is the identifier of the template string, if we If we need to use backticks in the string, we need to escape them, as shown below:
`No matter\` what you do,
I trust you.`
5. Note: If you use template strings to represent multi-line strings, all spaces and indents will be saved in the output! !
console.log( `No matter\` what you do, I trust you.`);
The output result is as follows:
6. You can put any JavaScriptexpression## in the curly brackets in ${} #, you can also perform operations and reference object properties.
var x=88; var y=100; console.log(`x=${++x},y=${x+y}`);
function string(){ return "zzw likes es6!"; } console.log(`你想说什么?嗯,${string()}`);
function string(){ return 666; } console.log(`你想说什么? 嗯,${string()}`);
console.log(`你想说什么? 嗯,${string()}`);
console.log(`你想说什么?嗯,${"其实我不是变量~"}`);
let str="return"+"`Hello! ${name}`"; let func=new Function("name",str); console.log(func("zzw"));
How to implement a custom multi-selection event for WeChat applet
How to create-react- The app is modified to support multiple pages
The above is the detailed content of How to use ES6 template strings. For more information, please follow other related articles on the PHP Chinese website!