基於外加的特性,用 const 必須在宣告的時候設值。
- 正確用法
const PI = 3.14;
- 錯誤用法
const PI;
PI = 3.14; // 不可重新設值
注意
用 const 宣告的變數,它的屬性(property)還是可以改寫。
- 物件(object)
const employee = { name: 'Shawn', dept: 'MKPL', age: 18 };
employee.name = 'Ray'; // 可以改寫屬性
employee = { name: 'Ray', dept: 'MKPL', age: 28 }; // 不可重新設值
- 陣列(array)
const fruits = ['Apple', 'Banana'];
fruits.push('Watermelon'); // 可以改寫屬性
fruits = ['Apple', 'Banana', 'Watermelon']; // 不可重新設值
沒有留言:
張貼留言