JavaScript ES6字符串模板语法的一个令人困惑的示例

时间:2019-05-10 02:42:18

标签: javascript ecmascript-6

我已经从某个JavaScript/Node.js项目中阅读了一些代码(似乎是ES6),我对语法感到困惑:

var c  = `
   export const imports = () => {
     const mods = []
     ${files.map((v) => `
['1234', 333]
`)}
     return Promise.all(mods)
   }
   export default imports
 `

这会给我

> c
'\n   export const imports = () => {\n     const mods = []\n     \n[\'1234\', 333]\n,\n[\'1234\', 333]\n\n     return Promise.all(mods)\n   }\n   export default imports\n '

如果在Node.js中运行。

我猜想这是一个多行字符串,我尝试过:

var s = `
    some multiline
    indented string`
['1234', 333]
`another multiline
    indented string
  `

但是我得到了三个子句:

> var s = `
...     some multiline
...     indented string`
undefined
> ['1234', 333]
[ '1234', 333 ]
> `another multiline
...     indented string
...   `
'another multiline\n    indented string\n  '

任何人都可以帮助我使用语法吗?它使用哪个ECMAScript规范?希望有人可以给我特定规格锚点的链接。

1 个答案:

答案 0 :(得分:2)

这是template literals的示例。

请注意,$ {...}中的部分是字符串插值-在这种情况下,令人困惑的是,插值本身(下面的代码)包括文字字符串。

 files.map((v) => `
['1234', 333]
`)