字符串模版标签用法

{
    /**
    * 字符串标签模版
    * @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都会设置一个默认的空字符''

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