ES6_字串模板

更新字串模板

過去我們撰寫字串的時候都是使用”型態,這種寫法會讓程式碼變得很攏長且難以閱讀,再多行的時候也必須插入反斜線來換行。ES6 借鏡了許多開發工具,可以使用 反引號 來插入一段字串,並且可以使用 ${} 來加入變數或函式,省去一堆 +來做串接。

原生寫法

1
const msg = "I am "+ age +" years old";

ES6寫法

1
2
3
4
const msg = `
I am ${age *2} years old.
I have ${brother} brothers and ${sister} sisters.
`;

解構陣列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

// 原始寫法
const point = [1,2,3];
const x = point[0];
const y = point[1];
const z = point[2];

// ES6作法
const point = [1,2,3]
const [x,y,z] = point;

//只取第一個
const [x] = point;

//只取第二個,用「,」捨去前面的
const[,y] = point

//取第一個跟其他的,用「...」代表
const[x,...others] = point;//others 代表一個陣列[2,3]

//給予預設值,當長度不夠時,會自動補植
const[x,y,z,w = 0] = point;

解構物件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

//原始寫法
const point ={ x:1, y:2, z:3 };
const x = point.x;
const y = point.y;
const z = point.z;

//ES6寫法
const { x, y, z} = point;

//只取一個值
const { x } = point;

//只取x跟其他的
const { x, ...others} = point//other代表{y:2, z:3}

//給予預設值,如果原本point裡面沒有值,就會給它預設值
const { x=0, w=0 } = point;//x還是1, w是0

//重新命名
const { x:px=0 } = point;//px是1,可是x會是undefined

物件用於函式

1
2
3
4
5
6
7
8
9
10
11

// 原始寫法
const point ={ x:1, y:2, z:3 };
const draw = point=>{
console.log(point);
}

//解構寫法
const draw = ({x,y,z})=>{
draw(point);//印出1 2 3
}