【问题标题】:javascript console.log new feature with 'raw'? [duplicate]javascript console.log 带有“原始”的新功能? [复制]
【发布时间】:2017-03-08 11:12:38
【问题描述】:

我遇到过这个例子,完全迷失了......

const test = (hey) => console.log(hey);

console.log(test `wtf`); 

首先这一切都是有效的,在console.log中,它似乎是

["wtf", raw: Array[1]]

好像函数被执行了,还有额外的raw?有人可以解释一下吗?

【问题讨论】:

标签: javascript ecmascript-6 template-literals tagged-templates


【解决方案1】:

这只是一个Tagged Template Literal。它看起来很花哨,但并没有什么特别之处。请注意,它们是 ES6/ES2015 的一部分,因此如果您计划支持旧版浏览器,则需要对它们进行转换。

模板文字是允许嵌入表达式的字符串文字。您可以使用多行字符串和字符串插值功能。在 ES2015 / ES6 规范的早期版本中,它们被称为“模板字符串”。

【讨论】:

    【解决方案2】:

    感谢@karmuran 和@deceze

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals

    原始字符串

    标记模板文字的第一个函数参数上可用的特殊原始属性允许您在输入原始字符串时访问它们。

    function tag(strings, ...values) {
      console.log(strings.raw[0]); 
      // "string text line 1 \n string text line 2"
    }
    
    tag`string text line 1 \n string text line 2`;
    

    【讨论】:

      猜你喜欢
      • 2012-03-16
      • 2023-02-10
      • 2013-12-25
      • 1970-01-01
      • 2012-07-09
      • 2023-03-28
      • 1970-01-01
      • 2010-11-11
      • 2014-04-13
      相关资源
      最近更新 更多