zoukankan      html  css  js  c++  java
  • 模板字符串

    作为JavaScript的未来,ES6已经到来。作为已完成的标准,ES6带来了许多新特性使其在如今的web世界仍有竞争力。ES6的方方面面不一定全都适合你,本文集会简要介绍一些顺手且可行的新特性。

    我编写JavaScript代码更喜欢使用单引号来定义字符串,而不是双引号。对JavaScript来说两者都可以,下面的两行代码其实作用相同:

    1. var animal = "cow";
    2. var animal = 'cow';
     

    我更喜欢单引号是有原因的。首先,单引号在组合使用HTML字符串和引用属性时更加方便。

    1. // with single quotes, there's no need to
    2. // escape the quotes around the class value
    3. var but = '<button class="big">Save</button>';
    4. // this is a syntax error:
    5. var but = "<button class="big">Save</button>";
    6. // this works:
    7. var but = "<button class="big">Save</button>";
     

    只有在 HTML 中使用单引号之时才需要转义,而HTML中是极少使用单引号的。我能想到的场景无非是内联 JavaScript 或 CSS,也就是说此时写的东西是靠不住的或者极度依赖标记语言。而在正文中,还不如使用排版更悦目的`‘`而不是单引号`'`。[^注: 也就是说不用转义了。]

    旁注: 当然,HTML相当宽容,你大可以删除引号或者转而使用单引号来包裹属性,但是我宁愿写可读性更好的标记语言而不是过分依赖语法分析程序。如今的HTML5语法分析程序如此宽容是因为过去人们写的标记语言太糟糕了,这不是继续糟糕下去的借口。
    在 DHTML 时代在框架集内部使用 document.writer 在新弹出窗口上创建文档之类的令人恶心的事情我已经受够了。我再也不要使用转义字符了。我甚至有时候还会用到三引号,这还是在编辑器有彩色高亮之前的事。简直是一团糟。
     

    在字符串中使用变量替换

    我更喜欢单引号还有一个原因。在编写高性能要求的网站时候我会大量使用PHP,而PHP是区分单引号和双引号的。PHP的单引号不允许字符串内变量替换,而双引号允许。

    也就是说在 PHP 3 和 PHP 4 时代使用单引号的效率更高,因为语法分析程序省去了检索整个字符串进行变量替换的麻烦。看下面的例子你就明白了:

    1. <?php $animal = 'cow';
    2. $sound = 'moo';
    3. echo 'The animal is $animal and its sound is $sound';
    4. // => The animal is $animal and its sound is $sound
    5. echo "The animal is $animal and its sound is $sound";
    6. // => The animal is cow and its sound is moo
    7. ?>
     

    JavaScript不支持字符串内的变量替换,所以不得不使用拼接字符串来代替。这显然太麻烦了,不得不频繁地在引文内和引文外来回切换。 

    1. var animal = 'cow';
    2. var sound = 'moo';
    3. alert('The animal is ' + animal + ' and its sound is ' +
    4. sound);
    5. // => "The animal is cow and its sound is moo"
     

    多行字符串的麻烦 

    在处理越来越长的字符串,尤其是组合使用大量 HTML 的时候真的是麻烦异常。而且很可能到头来 Linting 工具会报错说行末的 + 后面有个多于的空格。这问题完全是因为JavaScript不支持多行字符串。

    1. // 这样写是不行的:
    2. var list = '<ul>
    3. <li>Buy Milk</li>
    4. <li>Be kind to Pandas</li>
    5. <li>Forget about Dre</li>
    6. </ul>';
    7. // 可以这样写,但是,呃
    8. var list = '<ul>
    9. <li>Buy Milk</li>
    10. <li>Be kind to Pandas</li>
    11. <li>Forget about Dre</li>
    12. </ul>';
    13. // 这是最常见的写法,但是,呃
    14. var list = '<ul>' +
    15. ' <li>Buy Milk</li>' +
    16. ' <li>Be kind to Pandas</li>' +
    17. ' <li>Forget about Dre</li>' +
    18. '</ul>';
     

    客户端的模板解决方法

    为了在搞定麻烦的JavaScript字符串处理和拼接问题,还是得走到老路上,写个库。现有的众多HTML模板库中,Mustache.js 大概是影响力最大的。这些库大都遵循自定的非标准语法,使用起来完全看心情。打个比方,这就像是你用markdown格式写东西,然后意识到”markdown”本身就有很多不同的意思。[注:markdown有众多风格]

    使用模板字符串

    随着ES6及其标准的到来,我们欣喜地发现使用JavaScript处理字符串时可以使用模板字符串了。现在主流浏览器对模板字符串的支持非常及时:Chrome 44+, Firefox 38+, Microsoft Edge 和 Webkit 全部支持。遗憾的是 Safari 尚未支持,但是也不会等很久。

    模板字符串的设计天才之处在于使用了全新的字符串限定符,即在HTML和寻常文本中皆不常见的反引号(`)。

    1. var animal = 'cow';
    2. var sound = 'moo';
    3. alert(`The animal is ${animal} and its sound is ${sound}`);
    4. // => "The animal is cow and its sound is moo"
     

    ${} 接受任意的 JavaScript 表达式并返回相应值,可以用来进行数学运算或者访问对象的属性等等。

    1. var out = `ten times two totally is ${ 10 * 2 }`;
    2. // => "ten times two totally is 20"
    3. var animal = {
    4. name: 'cow',
    5. ilk: 'bovine',
    6. front: 'moo',
    7. back: 'milk',
    8. }
    9. alert(`
    10. The ${animal.name} is of the
    11. ${animal.ilk} ilk,
    12. one end is for the ${animal.front},
    13. the other for the ${animal.back}
    14. `);
    15. // =>
    16. /*
    17. The cow is of the
    18. bovine ilk,
    19. one end is for the moo,
    20. the other for the milk
    21. */
     

    第二个例子表明多行字符串再也不是个问题啦。

    标签化的模板

    还可以在模板字符串之前加上一个标签,用作函数名,可以调用这个函数而字符串就是参数。下面的例子实现了对返回的字符串进行编码生成URL,避免总是使用不友好的 namedencodeURIComponent。

    1. function urlify (str) {
    2. return encodeURIComponent(str);
    3. }
    4. urlify `http://beedogs.com`;
    5. // => "http%3A%2F%2Fbeedogs.com"
    6. urlify `woah$£$%£^$"`;
    7. // => "woah%24%C2%A3%24%25%C2%A3%5E%24%22"
    8. // nesting also works:
    9. var str = `foo ${urlify `&&`} bar`;
    10. // => "foo %26%26 bar"
     

    这样是能用是能用,却依赖于隐式的数组到字符串的强制转换。传递给函数的元素并不是字符串,而是字符串和值构成的数组。如果像上面这样使用,为了方便会被自动转换成字符串,但是正确的方法是直接访问数组成员。

    在模板字符串中检索字符串和值

    在标签函数内部,不仅可以使用完整字符串,还可以只使用字符串的一部分。

    1. function tag (strings, values) {
    2. console.log(strings);
    3. console.log(values);
    4. console.log(strings[1]);
    5. }
    6. tag `you ${3+4} it`;
    7. /* =>
    8. Array [ "you ", " it" ]
    9. 7
    10. it
    11. */
     

    你还可以使用原始字符串的数组,这意味着可以获取字符串中的所有字符,这里说的「所有」是指包括控制字符[^注:非打印字符]。比如在添加换行时使用的 就是控制字符。在字符串中只能得到两个空格,而在原始字符串中可以取得 字符。

    1. function tag (strings, values) {
    2. console.log(strings);
    3. console.log(values);
    4. console.log(strings[1]);
    5. console.log(string.raw[1]);
    6. }
    7. tag `you ${3+4} it`;
    8. /* =>
    9. Array [ "you ", " it" ]
    10. 7
    11. it
    12. it
    13. */
     

    结论

    模板字符串是ES6引入的超赞小特性,现在就可以使用。如果需要支持更老旧的浏览器,当然还可以把 ES6 转换编译 [注:transpile] 回 ES5。还可以针对模板字符串做一下特性检测,使用诸如 featuretests.io 的库,或者用下面的代码:

    1. var templatestrings = false;
    2. try {
    3. new Function( "`{2+2}`" );
    4. templatestrings = true;
    5. } catch (err) {
    6. templatestrings = false;
    7. }
    8. if (templatestrings) {
    9. // …
    10. }原文链接:http://www.gbtags.com/gb/share/9579.htm
  • 相关阅读:
    Postman模拟后端服务(mock server)
    Fiddler常用的几个功能
    Postman常用的几个功能
    Postman常用功能详解,常用请求方法
    sql小技巧
    postman接口数据关联
    postman批量发送多个请求
    sql去重查询语句
    pytho接口自动化-session
    charles抓包使用教程
  • 原文地址:https://www.cnblogs.com/gbtagscom/p/5033469.html
Copyright © 2011-2022 走看看