java中s标签_javasript 标签函数

javasript 标签函数

说实话javasript 标签函数使用的场景还是比较少的,以至于某个同学问到我这个问题时就懵逼了!!

什么是标签函数

标签函数的语法是函数名后面直接带一个模板字符串,并从模板字符串中的插值表达式中获取参数

举个例子:

let a = 5;

let b = 10;

function tag(s, v1, v2) {

console.log('begin----------');

console.log(s[0]);

console.log(s[1]);

console.log(s[2]);

console.log(v1);

console.log(v2);

}

tag`hello ${a + b} word ${a*b}` //标签函数1

tag`hello 12 word` //标签函数1

一般而言,我们调用函数是这样的 tag(hello ${a + b} word ${a*b}) 有没有发现区别?没错!!标签函数是后面直接跟模版字符串,而函数调用是有()的,里面是参数。比如tag(“参数1”)

进一步理解

tag`hello ${a + b} word ${a*b}` //标签函数1

tag`hello 12 word` //标签函数1

tag"hello asdf asdfg"// 错误语句

tag(`hello ${a + b} word ${a*b}`)//常规的函数调用

tag("hello word")//常规的函数调用

第一个、第二个后面跟的是标签字符串,所以为标签函数,第三个后面的字符串是用""号的,并不是标签语句,语句错误。可能到这里某些同学还不是很好理解,因为他不知道什么是模板字符串,下面我介绍模板字符串,看完后可返回在看一下这一块就很好理解了

模板字符串

模板字符串也是字符串。 只是一般的字符串没办法在字符串里面使用变量或者拼接,模板字符串可以

模板字符串语法

在 JavaScript 中编写字符串时,通常使用 ( ' )或者 ( " ),而模板字符串使用 (`)

普通字符串:

const str1 ='hello world';

const str2 ="hello world";

模板字符串:

const str3 =`hello world`;

字符串拼接

模板字符串写法可以直接使用 ${value} 嵌入表达式: let a = 5;

let b = 10;

let str = `hello ${a} word ${a + b}`

console.log(str);

hello 5 word 15 //输出结果

这里可以明显看出模板字符串的优势,很方便对字符串进行处理

标签函数的就是函数名后面直接带一个模板字符串

标签函数参数

let a = 5;

let b = 10;

let str = `hello ${a+b} word ${a*b} word`

第一个参数是被嵌入表达式分隔的文本的数组

在上面标签函数被分割的文本数组为['hello','word', 'word']

第二个参数开始是嵌入表达式的内容

在上面标签函数开始是嵌入表达式的内容为 ${a + b} ${a*b}

下面是输出例子 let a = 5;

let b = 10;

function tag(...args) {

console.log(args);

}

tag`hello${a + b}word${a*b}`;

tag`hello${a + b}`;

tag`hello${a + b}aaa`;

tag`hello`;

tag('我是一般函数');

/**下面是输出结果**/

[ [ 'hello', 'word', '' ], 15, 50 ]

[ [ 'hello', '' ], 15 ]

[ [ 'hello', 'aaa' ], 15 ]

[ [ 'hello' ] ]

[ '我是一般函数' ]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值