如何调用本机es6模板字符串替换从标签功能? [英] How to call native es6 template string replacement from tag function?

查看:220
本文介绍了如何调用本机es6模板字符串替换从标签功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为模板文字编写一个es6标签函数,它首先检查字符串中的一个条件,如果没有找到该条件,则只会将模板文字解释为未标记。我很好奇,如果从我的标签功能,有一种方法来调用浏览器的本机模板文字功能(我认为比我自己实现的功能更快)。 Bonue:有了这个标签组合的机会,例如htmlEscape(unindent foobar );



如。

 函数dumbTag(strs,... vals){
vals = vals.map((val,i) =>
(i%2 == 0?'even:':'odd:')+ val);
return String.template(strs,... vals);
}

我自己实现的功能 - 有更快的方式/方式调用浏览器的作用?

 函数模板(strs,... vals){
let result = strs [0];
for(let [i,val] of vals.entries()){
result + = val;
result + = strs [i + 1];
}
返回结果;
}


解决方案

没有这样的内置函数 - 未标记的模板文字只是被直接评估为字符串。


有更快的方法吗?




这取决于很多实现。如果您使用的是透明的,我将避免使用休息参数,迭代器和循环的

 函数模板(strs){
var result = strs [0]; (var i = 1; i< strs.length; i ++){
result + = arguments [i];

result + = strs [i];
}
返回结果;
}


I'm writing a es6 tag function for template literals, which first checks a condition in the string and, if the condition isn't found, merely interprets the template literal as if it were untagged. I am curious if, from my tag function, there is a way to call the browser's native template literal function (which I assume would be faster than my own implemented function). Bonue: With this, couldn't there be an opportunity for tag composition, eg htmlEscape(unindentfoobar);

eg.

function dumbTag(strs, ...vals) {
    vals = vals.map((val,i) =>
            (i % 2 == 0 ? 'even:' : 'odd:')+val);
    return String.template(strs, ...vals);
}

my own implemented function - is there a faster way / way to call what the browser does?

function template(strs, ...vals) {
    let result = strs[0];
    for (let [i,val] of vals.entries()) {
        result += val;
        result += strs[i+1];
    }
    return result;
}

解决方案

There is no such builtin function - untagged template literals are just evaluated straight to strings.

is there a faster way?

That depends a lot on the implementation. In case you are using a transpiler, I would avoid using rest parameters, iterators and for of loops:

function template(strs) {
    var result = strs[0];
    for (var i=1; i < strs.length; i++) {
        result += arguments[i];
        result += strs[i];
    }
    return result;
}

这篇关于如何调用本机es6模板字符串替换从标签功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆