0
点赞
收藏
分享

微信扫一扫

JS中将标签函数前缀到参数数量不同的模板字面量

是她丫 2022-05-01 阅读 96

标签函数的简单应用请见上篇讲述

JavaScript中模板字面量定义标签函数_咱们布奇的博客-CSDN博客JavaScript中模板字面量定义标签函数https://blog.csdn.net/sinat_21237645/article/details/124521305?spm=1001.2014.3001.5501

对于前缀到参数数量不固定表达式的标签函数,我们可以用剩余操作符(rest operator) 来处理参数。从而可以将同一标签函数前缀到参数数量不同的模板字面量前面来进行读取。

例如:

const a = `Hello`;
const b = `Amy`;
const c = `Hi`;
const d = `Sherry`;
const f = `Good morning`;

function Tag(strings, ...expressions) {
	console.log(strings); //输出模板字面量的每个插值之间的间隔符,组成数组

	for(const expression of expressions) {
		console.log(expression); //输出模板字面量的所有插值
	}

	return `${expressions[0]}, Leo!
${expressions[2]}, ${expressions[3]}~`; //返回自定义重组的模板字面量,插值从expressions数组中进行提取
}

const res1 = Tag`${a} ${b}, ${c} ${d}`; //将标签函数前缀到模板字面量
console.log(res1); 
//输出自定义重组的模板字面量
//Hello, Leo!
//Hi, Sherry~

const res2 = Tag`${f} Maria, ${f} Joe, ${f} ${b}, ${f} ${d} :)`; //将同一标签函数前缀到另一插值数量不同的模板字面量
console.log(res2);
//输出自定义重组的模板字面量
//Good morning, Leo!
//Good morning, Amy~

可以试着执行一下哦~

举报

相关推荐

0 条评论