使用撇号与单引号/反引号 [英] Use of apostrophe vs single quote/backtick

查看:372
本文介绍了使用撇号与单引号/反引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular的新手,在编写教程时,我在编写模块时略微改变习惯:

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 }');
      }
    },

这在项目的其余部分完全编译,没有错误。但是,当打电话时对于这个函数,它将 get 内容读作整个字符串,而不是按原样解析内容。

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 '

作为一名程序员我几乎差不多在参数中使用javascript和/或双引号时,总是专门使用单引号,所以这让我感到惊讶,并没有立即显现出来。这种行为是否有理由在某处记录?我应该养成使用反引号而非单引号的习惯吗?我想避免其他这样的惊喜。

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.

推荐答案

反引号是字符串插值工作所必需的。这是一个名为模板插值的ES6功能: https:// developer .mozilla.org / zh-CN / docs / Web / JavaScript / Reference / Template_literals

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.

有时它可供您使用,但它仍然可用远非广泛的浏览器支持 https://caniuse.com/#feat=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!

这篇关于使用撇号与单引号/反引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆