Types
#HelloFrontend #HelloErmine #HelloWorld2021
Type คืออะไร ?
คือ ประเภทของค่าที่เราสามารถใช้ได้ ที่พบเห็นได้บ่อยจะมีอยู่ 8 ชนิด คือ number, boolean, undefined, null, object, array, string และ function
number
เป็นค่าตัวเลข เก็บได้ทั้งจำนวนเต็มและทศนิยม
let num1 = 3000;
let num2 = 11.50;
console.log(typeof num1); // number
console.log(typeof num2); // number
boolean
เป็นค่าความจริง มีสอง keyword คือ true และ false
console.log(typeof true); // boolean
console.log(typeof false); // boolean
undefined
เป็นค่าที่บอกว่าตัวแปรยังไม่ถูกกำหนดค่าให้
let huh;
console.log(huh); // undefined
null
เป็นค่าที่แสดงถึงความว่างเปล่า
let nully = null;
console.log(nully); // null
object
เป็นตัวที่สามารถเก็บค่าแบบ key-value pair ได้ คือ เราใช้ key (หรืออีกชื่อคือ property) เพื่อเข้าถึง value ที่เกี่ยวข้องกับ key นั้น ๆ
let aCat = {
color: "black",
age: 5,
isSleeping: true
};
console.log(aCat); // {color: "black", age: 5, isSleeping: true}
console.log(aCat.color); // black (dot notation)
console.log(aCat["age"]); // 5 (bracket notation)
console.log(typeof aCat); // object
จากตัวอย่าง aCat
คือ object ที่มี key เป็น color
, age
และ isSleeping
ส่วน value จะอยู่หลัง colon (:) และแต่ละ key-value pair จะคั่นด้วย comma (,)
การเข้าถึงค่าใน object
สามารถทำได้ 2 แบบ คือ
dot notation (
obj.key
)bracket notation (
obj["key"]
)
array
เป็นค่าที่สามารถเก็บค่าอื่น ๆ ในตัวมันเองได้ สามารถเข้าถึงค่าข้างในผ่าน bracket notation ด้วย index หรือตำแหน่งใน array (เริ่มต้นจาก 0) เช่น arr[0]
การใช้ typeof กับค่า array ใน JavaScript จะได้ผลลัพธ์เป็น object (ให้มองเหมือนเป็น object ที่มี key เริ่มจาก 0, 1, 2, … ไปเรื่อย ๆ)
ถ้าอยากรู้ว่าตัวแปรเป็นค่า array หรือไม่ ให้ใช้ Array.isArray()
let arr = [27, "Huh", true];
let sussy = {
0: 27,
1: "Huh",
2: true
};
console.log(arr[1]); // Huh
console.log(sussy[1]); // Huh
console.log(typeof arr); // object
console.log(typeof sussy); // object
console.log(Array.isArray(arr)); // true
string
เป็นค่าข้อมูลตัวอักษรหรือข้อความ จะล้อมรอบด้วย double quote (“) หรือ single quote (‘) ก็ได้
let str1 = "School was Pog today xqcL";
let str2 = 'No';
console.log(typeof str1); // string
console.log(typeof str2); // string
function
อ่านเพิ่มเติมที่ Functions
function myFunc() {
console.log("This is a function");
}
console.log(typeof myFunc); // function
แหล่งอ้างอิง 📑
Last updated
Was this helpful?