※ ES6 變數宣告介紹:
在ES6中,推薦使用let和const取代原有的var來宣告變數。
※ var的特點:
- 勢力範圍(scope)只有兩種:function、global(全域部分)。
- 可以在宣告變數之前就使用。
※ var的缺點:
- 勢力範圍劃分不夠細緻。
- 宣告變數之前就使用,會造成潛在的風險。
※ let的特點:
- 勢力範圍(scope)永遠僅作用在{}之間。
也就是if、else、for和while迴圈,都可以有自己的局部變數。
- 不可以在宣告變數之前就是使用,屏除掉潛在風險。
※ const的特點:
- 用來宣告不可變動的內容。也就是一經宣告後,內部的值就不能再被變更。
※ ES6 變數的解構賦值:
※ 什麼是解構賦值:
是一種從陣列或物件中提取值,並將這些值賦給新的變數。好處是在處理多個變數賦值時,能更簡潔和清晰。
// 從陣列中提取值並賦值給變數
const [a, b] = [1, 2]
console.log(a); // 1
console.log(b); // 2
// 從物件中提取值並賦值給變數
const person = { name: 'Alice', age: 25 }
const { name, age } = person
console.log(name); // Alice
console.log(age); // 25
※ 解構賦值中的「...」:
可以說是展開運算符或剩餘運算符。在陣列和物件解構賦值中,用來提取出剩餘的值或屬性。
// 陣列
const numbers = [1, 2, 3, 4, 5]
const [a, b, ...rest] = numbers
console.log(a) // 1
console.log(b) // 2
console.log(rest) // [3, 4, 5]
// 物件
const person = {
name: 'Bob',
age: 30,
city: 'New York',
profession: 'Developer'
};
const { name, ...details } = person
console.log(name) // Bob
console.log(details) // { age: 30, city: 'New York', profession: 'Developer' }
//將收集剩餘的屬性到一個新的物件中。
const person = { name: 'Alice', age: 25, city: 'Wonderland', occupation: 'Adventurer' }
const { name, age, ...rest } = person
console.log(name); // Alice
console.log(age); // 25
console.log(rest); // { city: 'Wonderland', occupation: 'Adventurer' }
※ ES6解構賦值總結:
- 可以使用「...」做為陣列或物件剩餘資料的蒐集。
- 可以使用「...」做為將陣列或物件展開給新的陣列或物件的簡易方法。