# 概述
在ES6引入模板字符串之前,如果大家需要在代碼中創建一個包含變量的字符串,那么代碼將非常難讀,并且也非常容易出錯。下面就是一個簡單的例子,在例子中我們將輸入的3個參數拼接在一起,然后返回給調用方。
```javascript
//在模板字符串出現前的寫法,寫法冗長而且難于理解
function returnSomthing(param1, param2, param3){
return "something return based on input("
+ "param1:" + param1.toString() + "---"
+ "param2:" + param2.toString() + "---"
+ "param3:" + param3.toString();
}
//使用模板字符串的寫法,
function returnSomthingNew(param1, param2, param3){
return `something return based on input(
param1:${param1}---param2:${param2}---param3:${param3}`;
}
```
通過上面的代碼,你可以看出在使用模板字符串之后,代碼變得非常簡潔,而且也容易閱讀。下面是在使用模板字符串時候的一些注意點
* 模板字符串是使用 **`** 引用起來的,如果在最終生成的字符串中包含`字符,那么需要使用\字符進行轉義
* 模板字符串中對于變量的引用是通過${}來進行的
* 使用模板字符串的時候,${}中可以放入任意合法的JavaScript表達式。JavaScript對包含在${}中的內容實際上是通過eval表達式來進行的
# 標簽模板
模板字符串可以跟在一個函數名之后,該函數將被調用來處理跟在后面的模板字符串,這個功能被稱為標簽模板。被調用的函數將接收到下面的參數列表(literals,...values)。其中literals是一個數組,內容是模板字符串中不需要進行變量替換的部分,而values就是每個替換變量經過eval之后的值,下面是一個具體的例子。
```javascript
var total = 30;
var msg = transform`The total number is ${total}`;
total = 20;
var msg1 = transform`The total number is ${total}`;
//in our sample
//literals = ["The total number is ", ""]
//values = [30]
function transform(literals,...values){
var output = "";
for (var index = 0; index < values.length; index++){
if (parseInt(values[index]) >= 30){
output += literals[index] + "high value";
}else{
output += literals[index] + "low value";
}
}
output += literals[index];
return output;
}
console.log(msg); //output The total number is high value
console.log(msg1);//output The total number is low value
```
- Introduction
- Nodejs 4.x新特性
- classes
- typed arrays
- generators
- collections
- Set
- Map
- arrow functions
- block scoping
- template strings
- promises
- symbols
- Koa基礎
- 上下文
- koa-generator
- 安裝
- 創建項目
- 更改視圖模板引擎
- Routes
- HTTP
- Get
- 如何獲取query參數
- 如何獲取params
- Post
- 從post獲取參數
- 標準表單(Post with x-www-form-urlencoded)
- 文件上傳(Post with form-data)
- Post with raw
- 數據庫
- MySQL
- Mongo
- 流程控制
- generator/co
- es6的generator是什么?
- co = generator + promise
- async/await
- promise with bluebird
- 測試
- Mocha
- Supertest
- 部署
- 最佳實踐
- FAQ
- 如何發布本書到git pages
- 如何知道require模塊的用法
- koa中的異常處理