JaveScript-ES6-const

JaveScript-ES6-const

const用來宣告常數變數,一旦宣告就無法改變。

const-一旦宣告就無法改變

1
2
3
4
5
const PI = 3.1415;
PI // 3.1415

PI = 3;
// TypeError: Assignment to constant variable.

const一旦宣告,必須賦予初始值

1
2
const foo;
// SyntaxError: Missing initializer in const declaration

只在宣告的區塊內有效

1
2
3
4
5
if (true) {
const MAX = 5;
}

MAX // Uncaught ReferenceError: MAX is not defined

const只能在宣告後使用

1
2
3
4
if (true) {
console.log(MAX); // ReferenceError
const MAX = 5;
}

不可重複宣告

1
2
3
4
5
6
var message = "Hello!";
let age = 25;

// 以下兩行都error
const message = "Goodbye!";
const age = 30;

const不能改變記憶體位址

1
2
3
4
5
6
7
8
9
10
11
12
13
const foo = {};

// 可以在 foo 增加屬性
foo.prop = 123;
foo.prop // 123

// 将 foo 指向 { },error
foo = {}; // TypeError: "foo" is read-only
-------------------------------------------
const a = [];
a.push('Hello'); // ok
a.length = 0; // ok
a = ['Dave']; // error