本文主要介紹了深入淺出es6模板字符串,分享給大家,具體如下
作為前端開發(fā)者避免不了根據(jù)后臺(tái)數(shù)據(jù)的返回,組裝html,渲染頁面。舉個(gè)栗子
$('#result').append( 'There are <b>' + basket.count + '</b> ' + 'items in your basket, ' + '<em>' + basket.onSale + '</em> are on sale!');
有時(shí)候還要給標(biāo)簽加一些屬性,寫起來很不方便,es6提供了模板字符串的方法,簡化了這一過程
$('#result').append(` There are <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale!`);
所有模板字符串的空格和換行,都是被保留的,如果你不想要前后換行,可以使用trim方法消除它。
在{}你可以寫任意JavaScript表達(dá)式,包括調(diào)用函數(shù)
var x = 1;var y = 2;`${x} + ${y} = ${x + y}`// "1 + 2 = 3"`${x} + ${y * 2} = ${x + y * 2}`// "1 + 4 = 5"var obj = {x: 1, y: 2};`${obj.x + obj.y}`// "3"function fn() { return "Hello World";}`foo ${fn()} bar`// foo Hello World bar
如果變量沒有聲明,會(huì)報(bào)錯(cuò),如果{}中是一個(gè)字符串,則原樣返回
// 變量place沒有聲明var msg = `Hello, ${place}`;// 報(bào)錯(cuò)`Hello ${'World'}`// "Hello World"
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注