ES6 template string

The traditional JavaScript language output template usually is written like this (below uses jQuery methods).

$ ( '# Result'). the append (
'There are <B>' + basket.count + '</ B>' +
'items in your Basket,' +
'<EM>' + basket.onSale +
'</ EM> are ON would like to purchase '!
);
above this rather cumbersome wording is not convenient, ES6 introduced a template string to solve this problem.

$ ( '# Result'). the append ( `
There are <B> basket.count} {$ </ B> items
in your Basket, <EM> basket.onSale $ {} </ EM>
are ON Sale!
`) ;
template string (template string) is an enhanced version of the string ( `) identified by anti-quotation marks. It can be used as ordinary strings, it can also be used to define multiple rows of strings, or embedded in the string variable.

// Common string
`In JavaScript '\ n' is a line-feed.`

// multi-line strings
`an In JavaScript the this IS
not legal.`

console.log(`string text line 1
string text line 2`);

// string embedded variable
the let name = "Bob", Time = "Today";
`the Hello $ {name}, How are you $ {}` Time?
Template string code above, are represented by reverse quotes . If you need anti-quoted string in the template, the preceding backslash to use.

let greeting = `\` Yo \ `World`;!
If you use a template string representation of the multi-line strings, all spaces and indentation are preserved in the output being.

. $ ( '# List') HTML ( `
<UL>
<Li> First </ Li>
<Li> SECOND </ Li>
</ UL>
`);
the above code, all the templates strings spaces and line breaks, They are reserved, such as <ul> tag will be in front of a line break. If you do not want this wrap, you can use the trim method to eliminate it.

$ ( '# List') HTML ( `.
<UL>
<Li> First </ Li>
<Li> SECOND </ Li>
</ UL>
` .trim ());
template string embedded variables need to be variable names written into the $ {}.

function authorize(user, action) {
if (!user.hasPrivilege(action)) {
throw new Error(
// 传统写法为
// 'User '
// + user.name
// + ' is not authorized to do '
// + action
// + '.'
`User ${user.name} is not authorized to do ${action}.`);
}
}
大括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象属性。

let x = 1;
let y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"
模板字符串之中还能调用函数。

function fn() {
return "Hello World";
}

`foo ${fn()} bar`
// foo Hello World bar
如果大括号中的值不是字符串,将按照一般的规则转为字符串。比如,大括号中是一个对象,将默认调用对象的toString方法。

如果模板字符串中的变量没有声明,将报错。

// 变量place没有声明
let msg = `Hello, ${place}`;
// 报错
由于模板字符串的大括号内部,就是执行 JavaScript 代码,因此如果大括号内部是一个字符串,将会原样输出。

`Hello ${'World'}`
// "Hello World"
模板字符串甚至还能嵌套。

const tmpl = addrs => `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}</td></tr>
<tr><td>${addr.last}</td></tr>
`).join('')}
</table>
`;
上面代码中,模板字符串的变量之中,又嵌入了另一个模板字符串,使用方法如下。

const data = [
{ first: '<Jane>', last: 'Bond' },
{ first: 'Lars', last: '<Croft>' },
];

console.log(tmpl(data));
// <table>
//
// <tr><td><Jane></td></tr>
// <tr><td>Bond</td></tr>
//
// <tr><td>Lars</td></tr>
// <tr><td><Croft></td></tr>
//
// </table>
如果需要引用模板字符串本身,在需要时执行,可以写成函数。

let func = (name) => `Hello ${name}!`;
func('Jack') // "Hello Jack!"
上面代码中,模板字符串写成了一个函数的返回值。执行这个函数,就相当于执行这个模板字符串了。

 

Guess you like

Origin www.cnblogs.com/ranyonsue/p/11798080.html
Recommended