第四章 變量聲明
阿新 • • 發佈:2017-12-31
ava spi 原則 uml ret 你在 etc markdown 有變
變量聲明
一、let 和 const
let 和 const 是 JavaScript 裏相對較新的變量聲明方式。 let 在很多方面與 var 是相似的,但是可以幫助大家避免在 JavaScript 裏常見一些問題(如作用域提升)。 const 是對 let 的一個增強,它能阻止對一個變量再次賦值。
因為 TypeScript 是 JavaScript 的超集,所以它本身就支持 let 和 const。 推薦使用它們來代替 var。
使用最小特權原則,所有變量除了你計劃去修改的都應該使用 const。
二、代碼示例
//塊級作用域變量的獲取 function theCityThatAlwaysSleeps() { let getCity; if (true) { let city = "Seattle"; getCity = function() { return city; }; } return getCity(); } //重定義及屏蔽,這個版本的循環能得到正確的結果,因為內層循環的i可以屏蔽掉外層循環的i function sumMatrix(matrix: number[][]) { let sum = 0; for (let i = 0; i < matrix.length; i++) { var currentRow = matrix[i]; for (let i = 0; i < currentRow.length; i++) { sum += currentRow[i]; } } return sum; } //const 聲明 const numLivesForCat = 9; const kitty = { name: "Aurora", numLives: numLivesForCat }; // Error kitty = { name: "Danielle", numLives: numLivesForCat }; // all "okay" kitty.name = "Rory"; kitty.name = "Kitty"; kitty.name = "Cat"; kitty.numLives--;
三、解構
- 解構數組
//最簡單的解構 let input = [1, 2]; let [first, second] = input; console.log(first); // outputs 1 console.log(second); // outputs 2 // 交換變量 [first, second] = [second, first]; //作用於函數參數 function f([first, second]: [number, number]) { console.log(first); console.log(second); } f(input); //數組裏使用...語法創建剩余變量 let [first, ...rest] = [1, 2, 3, 4]; console.log(first); // outputs 1 console.log(rest); // outputs [ 2, 3, 4 ] //忽略你不關心的尾隨元素 let [first] = [1, 2, 3, 4]; console.log(first); // outputs 1 let [, second, , fourth] = [1, 2, 3, 4];
- 對象解構
//對象解構
let o = {
a: "foo",
b: 12,
c: "bar"
};
let { a, b } = o;
//就像數組解構,你可以用沒有聲明的賦值
({ a, b } = { a: "baz", b: 101 });
//你可以在對象裏使用...語法創建剩余變量
let { a, ...passthrough } = o;
let total = passthrough.b + passthrough.c.length;
- 屬性重命名
//你也可以給屬性以不同的名字 let { a: newName1, b: newName2 } = o;
- 默認值
//默認值可以讓你在屬性為 undefined 時使用缺省值
function keepWholeObject(wholeObject: { a: string; b?: number }) {
let { a, b = 1001 } = wholeObject;
}
- 函數聲明
//解構也能用於函數聲明
type C = { a: string; b?: number };
function f({ a, b }: C): void {
// ...
}
- 展開
//將一個數組展開為另一個數組
let first = [1, 2];
let second = [3, 4];
let bothPlus = [0, ...first, ...second, 5];
//將一個對象展開為另一個對象
let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
let search = { ...defaults, food: "rich" };
//註意:如果前後對象有相同的屬性,則後面的覆蓋前面的
第四章 變量聲明