2019年3月19日 星期二

[Back To Basic] Javascript - Const

用 const 宣告的變數擁有 let 所有特性,外加一個特性: 不可被重新設值
基於外加的特性,用 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'];  // 不可重新設值

瀏覽器支援: IE10以前不支援 const

沒有留言:

張貼留言