ชนิดข้อมูล (Data Type) คือประเภทของค่าที่ JavaScript ใช้ประมวลผล เช่น ข้อความ ตัวเลข ค่าจริงเท็จ รายการข้อมูล และ object
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart LR
A["JavaScript Values
ค่าข้อมูล"] --> B["Primitive Types
ชนิดพื้นฐาน"]
A --> C["Reference Types
ชนิดอ้างอิง"]
B --> D["String, Number, BigInt
ข้อความและตัวเลข"]
B --> E["Boolean, Symbol
ตรรกะและสัญลักษณ์"]
B --> F["null, undefined
ค่าว่างและยังไม่กำหนด"]
C --> G["Array
รายการข้อมูล"]
C --> H["Object
ข้อมูลแบบ key-value"]
| ชนิด | ตัวอย่าง | ความหมาย |
|---|---|---|
| String | "HTML" |
ข้อความ |
| Number | 42, 3.14 |
ตัวเลข |
| BigInt | 9007199254740993n |
จำนวนเต็มขนาดใหญ่ |
| Boolean | true, false |
ค่าจริง/เท็จ |
| Symbol | Symbol("id") |
ค่าที่ไม่ซ้ำ |
| null | null |
ตั้งใจให้เป็นค่าว่าง |
| undefined | undefined |
ยังไม่มีค่า |
typeoftypeof ใช้ตรวจสอบชนิดข้อมูล
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 (ข้อควรระวังทางประวัติศาสตร์)
const course = "Web Programming";
console.log(course.length); // จำนวนตัวอักษร
console.log(course.toUpperCase()); // แปลงเป็นตัวใหญ่
console.log(course.slice(0, 3)); // ตัดข้อความ
console.log(course.split(" ")); // แยกเป็น array
console.log(course.includes("Web")); // ตรวจว่ามีคำนี้ไหม
const week = 4;
console.log(`Week ${week}: ${course}`); // template literal
const ageText = "20";
const priceText = "99.50";
console.log(parseInt(ageText, 10)); // 20
console.log(parseFloat(priceText)); // 99.5
console.log(Number.isNaN(Number("abc"))); // true
console.log(1 / 0); // Infinity
Array คือรายการข้อมูลที่เข้าถึงด้วย index เริ่มจาก 0
const lessons = ["HTML", "CSS", "JavaScript"];
console.log(lessons[0]); // HTML
console.log(lessons.length); // 3
for (const lesson of lessons) {
console.log(`เรียน: ${lesson}`);
}
Object เก็บข้อมูลแบบ key-value
const user = {
name: "Ana",
age: 20,
active: true
};
console.log(user.name); // Ana
console.log(user["age"]); // 20
โดยที่ lastIndex คือ index สุดท้ายของ array และ length คือจำนวนสมาชิกทั้งหมดใน array
null และ undefined ต่างกันอย่างไรtypeof null ได้ค่าอะไร.split() ใช้ทำอะไรNumber.isNaN() ใช้ตรวจอะไร. และ [] ต่างกันอย่างไร