Use of apostrophe vs single quote/backtick

江枫思渺然 提交于 2020-01-14 09:03:26

问题


I'm new to Angular, and while following along to a tutorial I made a slight change out of habit when writing the module states:

.state('sports.medals', {
    url: '/:sportName',
    templateUrl: 'sports/sports-medals.html',
    resolve: {
      sportService: function($http, $stateParams){
        return $http.get('/sports/${ $stateParams.sportName }');
      }
    },

This compiles perfectly fine within the rest of the project, no errors. However, when the call is made to this function, it reads the get contents as one whole string instead of parsing the contents as it should.

The correct way to call this is apparently:

 .state('sports.medals', {
        url: '/:sportName',
        templateUrl: 'sports/sports-medals.html',
        resolve: {
          sportService: function($http, $stateParams){
            return $http.get(`/sports/${ $stateParams.sportName }`);
          }
        },

using the ` apostrophe/backtick instead of the single quote '

As a programmer I've almost always exclusively used the single quote when working with javascript and/or double-quotes within parameters, so this surprised me and wasn't immediately apparent. Is there a reason for this behavior that is documented somewhere? Should I get in the habit of using backticks over single quotes? I would like to avoid other such surprises.


回答1:


The backticks are necessary for the string interpolation to work. This is an ES6 feature called template interpolation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals.

Sometimes it will be available to you, but it is still far from widespread in terms of browser support https://caniuse.com/#feat=template-literals. Get familiar with it and use it when you can!




回答2:


Template literals are enclosed by the back-tick ` (grave accent) character instead of double or single quotes.

Template literals / string literals in javascript use the back tick. They are an E6 feature that is simply syntactic sugar for concatenation. Template literals are widely supported in modern browsers and are supported in nodejs. When not using templates you should either use double (") or single (') quotes.

MDN has documentation that will give more information on template literal use: Template literals



来源:https://stackoverflow.com/questions/42753169/use-of-apostrophe-vs-single-quote-backtick

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