ES6学习——新的语法:Tagged Templates

本文详细解析了JavaScript中模板字面量与标签函数的使用方式,并通过实例展示了如何利用这些特性来格式化输出及创建动态字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个概念我也不知道怎么解释,还是直接看规范给出的描述吧,在12.3.7章节:

A tagged template is a function call where the arguments of the call are derived from a TemplateLiteral (12.2.9). The actual arguments include a template object (12.2.9.3) and the values produced by evaluating the expressions embedded within the TemplateLiteral.


先看个简单的例子:

function foo(strings, ...values) {
    console.log( strings );
    console.log( values );
}

var desc = "awesome";

foo`Everything is ${desc}!`;
// [ "Everything is ", "!"]
// [ "awesome" ]

这个语法就是一个函数调用,前面的foo是个函数,形参是template literal,实参的第一个参数是个数组对象,数组个数是template中变量个数加1,也就是说数组的元素相当于用split函数分割了模板,如下:

"Everything is ${}!${}".split(/\$\{[^\}]*\}/)//["Everything is ", "!", ""]

其实第一个参数中还有个属性叫raw,如果们console.log(strings.raw),也能打印出一个数组,这个数组中的元素相当于每个都是用String.raw处理过一样,上篇文章中我们讲到过这种用法。


函数的第二个实参相当于template中变量的实际值,上面用rest操作符做了处理。


这样解释完了,应该对这个特性有点了解了吧。下面看个简单应用,格式化货币的小数位:

function dollabillsyall(strings, ...values) {
	return strings.reduce( function(s,v,idx){
		if (idx > 0) {
			if (typeof values[idx-1] == "number") {
				s += `$${values[idx-1].toFixed( 2 )}`;
				//s += "$" + values[idx-1].toFixed( 2 );
			}
			else {
				s += values[idx-1];
			}
		}
		return s + v;
	}, "" );
}

var amt1 = 11.99,
amt2 = amt1 * 1.08,
name = "Kyle";

var text = dollabillsyall
`Thanks for your purchase, ${name}! Your
product cost was ${amt1}, which with tax
comes out to ${amt2}.`

console.log( text );


结果:
Thanks for your purchase, Kyle! Your
product cost was $11.99, which with tax
comes out to $12.95.


仔细看上面的例子,在number的if中应用上篇文章中讲的概念。

再看一个mozilla上的例子:

function template(strings, ...keys) {
  return (function(...values) {
    var dict = values[values.length - 1] || {};
    var result = [strings[0]];
    keys.forEach(function(key, i) {
      var value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });
    return result.join('');
  });
}

template`${0}${1}${0}!`('Y', 'A');  // "YAY!" 
template`${0} ${'foo'}!`('Hello', {foo: 'World'});  // "Hello World!"

上面这个用法更高级一点,template函数本身返回了一个函数,然后执行,去替换模板中的索引变量。


如果template literal前面不是函数会怎么样?报错

var aaa = 1;
aaa `Hello World!`//TypeError: aaa is not a function


*以上全部代码在Firefox 43下通过测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值