Difference (if there is any) between ` and ' in javascript [duplicate]

萝らか妹 提交于 2019-11-27 13:05:18

问题


This question already has an answer here:

  • Usage of the backtick character (`) in JavaScript? 7 answers

Recently ran into some JS code that uses ` and '. I can't figure out if there is a different use for each apostrophe. Is there any?


回答1:


' or " denote a string and ` denotes a template string. Template strings have some abilities that normal strings do not. Most importantly, you get interpolation:

var value = 123;
console.log('test ${value}') //=> test ${value}
console.log(`test ${value}`) //=> test 123

And multiline strings:

console.log('test
test')
// Syntax error

console.log(`test
test`)
// test
// test

They have some other tricks too, more on template strings here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

Note they are not supported in all javascript engines at the moment. Which is why template strings are often used with a transpiler like Babel. which converts the code to something that will work in any JS interpreter.



来源:https://stackoverflow.com/questions/33679732/difference-if-there-is-any-between-and-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!