gpt4 book ai didi

javascript - 在理解标记模板方面需要帮助

转载 作者:行者123 更新时间:2023-11-30 19:40:08 25 4
gpt4 key购买 nike

我有两个使用 tagged template 的代码片段模板文字的特点

代码一

function myTaggedLiteral(strings, value, value2) {
console.log(strings, value, value2);
}

let someText = 'Neat';
myTaggedLiteral `test ${someText} ${2 + 3} test2`;

在这种情况下它会记录

[
"test ",
" ",
" test2"
] Neat 5

这个例子来自mdn

var person = 'Mike';
var age = 28;

function myTag(strings, personExp, ageExp) {
console.log(strings, personExp, ageExp)
// some other code
}
var output = myTag `That ${ person } is a ${ age }`;

这将记录

[
"That ",
" is a ",
""
] Mike 28

所以在第一个日志中有一个空字符串 ""test 之后,我的理解是模板表达式 ${someText} ${2 + 3} 但在第二个日志中 That 之后没有 "" ,尽管这两个函数都是在几乎相同的参数结构中调用的。

如果有人帮助我理解为什么在第一个日志中测试后有一个空字符串,我将非常感激。

其次,如果我调整第一个程序

function myTaggedLiteral(strings, value, value2) {
console.log(strings);
}

let someText = 'Neat';
myTaggedLiteral `test test6 test3 ${someText} ${2 + 3}`;

这将记录

[
"test test6 test3 ",
" ",
""
]

根据 mdn

The first argument of a tag function contains an array of string values.

如果是这样,那为什么它输出的第一个值是 "test test6 test3 " 而不是 "test","test6","test3"

最佳答案

strings 参数想象成 String.prototype.split() 的结果其中分隔符是任何 placeholder , 又名

... indicated by the dollar sign and curly braces (${expression}).

举个例子

let templateString = 'test test6 test3 ${someText} ${2 + 3}'
let strings = templateString.split(/\$\{.*?}/) // regex for a placeholder

console.log(strings)

来自documentation ...

If separator appears at the beginning or end of the string, or both, the array begins, ends, or both begins and ends, respectively, with an empty string

这就是为什么,如果任何占位符出现在字符串的边界,您将在结果数组中得到空字符串。

在这一点上,您始终可以确保 strings 比占位符表达式多一个条目。创建结果字符串将始终涉及(忽略您可能想要做的任何额外转换)...

strings[0] + arg[0] +
strings[1] + arg[1] +
...
strings[n] + arg[n] + strings[n+1]

其中 n 是占位符的数量。

关于javascript - 在理解标记模板方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55487478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com