码迷,mamicode.com
首页 > 其他好文 > 详细

字符串模版标签用法

时间:2018-12-11 19:51:44      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:ring   OLE   hello   存在   意思   字符变量   模版   function   style   

{
    /**
    * 字符串标签模版
    * @arg {Array} literals - 被字符变量打散的字符串
    * @arg {Array} substitutions - 对应每个替换的变量值
    * @return {String} 新的字符串
    */
    const repeat = function(literals, ...substitutions) {
        console.log(`literals: ${literals.length}`)
        console.log(`substitutions: ${substitutions.length}`)
        /**
         * 注意listerals[0]
         * 在这个例子里面是‘‘,即为空字符串,
         * 意思是literals.length永远比substitutions.length长1
         * 即 substitutions.length + 1 === literals.length
         * 前题是literals与substitutions都存在的情况
         */
        return literals.reduce(( prev, next, index, arr ) => {
            const substitution = substitutions[index - 1];
            return prev + ( substitution ? (substitution + ‘ ‘).repeat(2) : ‘‘) + next.repeat(2);
        }, ‘‘)
    }
    const say = `say`
    const world = `world`;
    const str = repeat`${say}hello ${world}!`
    console.log(str)
}

这里需要注意的是无论${ variable }是在开头还是结尾,literals都会设置一个默认的空字符‘‘

字符串模版标签用法

标签:ring   OLE   hello   存在   意思   字符变量   模版   function   style   

原文地址:https://www.cnblogs.com/hellolol/p/10104257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!