變數與資料型別#

JavaScript 擁有動態型別系統——變數不需事先宣告型別,執行時自動判斷。 宣告變數使用 constletvar 三個關鍵字,現代寫法優先使用 constlet,不使用 var


宣告變數#

JavaScript 有三個宣告關鍵字:constletvar

1
2
3
const PI = 3.14159;   // 常數,不可重新賦值
let score = 100;      // 可重新賦值
var name = "舊式寫法"; // 避免使用

原則:優先用 const,需要重新賦值才用 let,不用 var


const 與 let 的差異#

1
2
3
4
5
6
const x = 10;
x = 20; // TypeError: Assignment to constant variable.

let y = 10;
y = 20; // 合法
console.log(y); // 20

注意:const 宣告物件或陣列時,內容仍可修改(參考位址不變):

1
2
3
4
5
const arr = [1, 2, 3];
arr.push(4);       // 合法
console.log(arr);  // [1, 2, 3, 4]

arr = [5, 6];      // TypeError(不可重新指派)

資料型別(Data Types)#

基本型別(Primitive)#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 字串(String)
const str1 = "雙引號";
const str2 = '單引號';
const str3 = `樣板字串 ${1 + 1}`; // "樣板字串 2"

// 數字(Number)
const int = 42;
const float = 3.14;
const neg = -100;

// 布林值(Boolean)
const isTrue = true;
const isFalse = false;

// undefined — 宣告了但未賦值
let undef;
console.log(undef); // undefined

// null — 明確表示「空值」
const empty = null;

// BigInt — 超大整數
const big = 9007199254740991n;

// Symbol — 唯一識別符(進階用途)
const sym = Symbol("id");

複合型別(Reference)#

1
2
3
4
5
6
7
8
// 物件(Object)
const user = { name: "Alice", age: 25 };

// 陣列(Array)
const nums = [1, 2, 3, 4, 5];

// 函式(Function)
function greet() { return "Hi"; }

typeof 運算子#

1
2
3
4
5
6
7
8
console.log(typeof "hello");     // "string"
console.log(typeof 42);          // "number"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object"(歷史遺留問題)
console.log(typeof []);          // "object"
console.log(typeof {});          // "object"
console.log(typeof function(){}); // "function"

型別轉換#

轉為字串#

1
2
3
4
String(42)       // "42"
String(true)     // "true"
(42).toString()  // "42"
`${42}`          // "42"(樣板字串自動轉換)

轉為數字#

1
2
3
4
5
6
7
8
Number("42")     // 42
Number("3.14")   // 3.14
Number("")       // 0
Number("abc")    // NaN
Number(true)     // 1
Number(false)    // 0
parseInt("42px") // 42(取整數部分)
parseFloat("3.14rem") // 3.14

轉為布林值#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Boolean(0)         // false
Boolean("")        // false
Boolean(null)      // false
Boolean(undefined) // false
Boolean(NaN)       // false
// 以上為 falsy 值,其餘皆為 true

Boolean(1)         // true
Boolean("hello")   // true
Boolean([])        // true(空陣列是 truthy!)
Boolean({})        // true(空物件是 truthy!)

樣板字串(Template Literals)#

反引號(`)讓字串插值更方便:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const name = "Alice";
const age = 25;

// 舊式字串拼接
const msg1 = "我叫 " + name + ",今年 " + age + " 歲。";

// 樣板字串(推薦)
const msg2 = `我叫 ${name},今年 ${age} 歲。`;

// 支援多行
const html = `
  <div>
    <p>${name}</p>
  </div>
`;

// 可放入表達式
console.log(`1 + 1 = ${1 + 1}`); // 1 + 1 = 2

變數命名規則#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// 合法命名
let userName = "camelCase 駝峰式(推薦)";
let user_name = "snake_case(較少用)";
let _private = "底線開頭";
let $element = "$ 開頭(常見於 jQuery)";
let count1 = "可包含數字(不可開頭)";

// 非法命名
let 1count = "錯誤:不可以數字開頭";
let user-name = "錯誤:不可含連字號";
let let = "錯誤:不可用保留字";

解構賦值(Destructuring)#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// 陣列解構
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3

// 跳過元素
const [first, , third] = [10, 20, 30];
console.log(first, third); // 10 30

// 物件解構
const { name, age } = { name: "Bob", age: 30 };
console.log(name, age); // Bob 30

// 重新命名
const { name: userName } = { name: "Carol" };
console.log(userName); // Carol

// 預設值
const { x = 0, y = 0 } = { x: 5 };
console.log(x, y); // 5 0

Reference#