基礎型態
型態決定一份資料能做什麼:數字能加減,字串能拼接,陣列能用編號取出項目。日常寫 Node.js,先把下面這些用熟就夠。
數字 number
整數與小數都是 number,沒有分開的整數型。typeof 用來查看一份資料目前是哪一種型態。
字串 string
文字叫字串(string)。單引號、雙引號都可以;反引號能把變數嵌進句子裡,寫成 ${變數}:
const name = "Ada";
const msg = `Hello, ${name}`;
console.log(msg);
console.log(name.length);
console.log(name.toUpperCase());
布林 boolean
布林只有 true(是)與 false(否),多半來自比較,之後給 if 判斷用:
null 與 undefined
兩者都表示「沒有值」,用意不同:
undefined:還沒給值,或物件上沒這個屬性。通常是「忘了設」或「找不到」。null:程式作者刻意寫上,表示「現在就是沒有」。
陣列 Array
陣列是一串有順序的資料。第一個項目編號是 0,不是 1;length 是項目個數,push 會在最後面加一筆。
物件 Object
物件用「名稱:值」存放一筆資料。用 user.name 讀取,也可以再指定把它改掉:
用 typeof 查看
console.log(typeof 1); // number
console.log(typeof "hi"); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object(歷史因素,記住即可)
console.log(typeof [1, 2]); // object
typeof null 與 typeof 陣列都會得到 "object",這是語言的歷史因素。要分辨陣列,用 Array.isArray(nums)。
總結
數字做計算,字串做文字,布林做判斷,陣列放列表,物件放一筆結構化資料。這五種覆蓋大多數初學程式。