Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความแตกต่างระหว่าง Primitive และ Non-Primitive Data Types ใน JavaScript

Primitive Types (ค่าประเภทพื้นฐาน)

  • Number: ตัวเลข (integer, float) - typeof 10 === 'number'
  • String: ข้อความ - typeof "John" === 'string'
  • Boolean: true/false - typeof true === 'boolean'
  • Undefined: ไม่ได้กำหนดค่า - typeof undefined === 'undefined'
  • Null: ค่าว่าง - typeof null === 'object' (bug แห่งนี้)
  • Symbol: ค่า unique (ES2015) - typeof Symbol() === 'symbol'
  • BigInt: จำนวนเต็มใหญ่ (ES2020) - typeof 10n === 'bigint'

Non-Primitive / Reference Types (ค่าประเภทอ้างอิง)

  • Object: {}, new Object() - typeof {} === 'object'
  • Array: [], new Array() - typeof [] === 'object'
  • Function: function() {} - typeof function(){} === 'function'
  • Date, RegExp, Map, Set, etc. - ล้วนเป็น Object

ตัวอย่างโค้ด


var number = 10;
var stringValue = "John";
var booleanValue = true;
var obj = {};
var newArray = new Array();

console.log("ชนิดข้อมูล number = " + typeof number);       // number
console.log("ชนิดข้อมูล stringValue = " + typeof stringValue); // string
console.log("ชนิดข้อมูล booleanValue = " + typeof booleanValue); // boolean
console.log("ชนิดข้อมูล obj = " + typeof obj);               // object
console.log("ชนิดข้อมูล newArray = " + typeof newArray);     // object

วิธีรัน

node fileName.js

ผลลัพธ์


ชนิดข้อมูล number = number
ชนิดข้อมูล stringValue = string
ชนิดข้อมูล booleanValue = boolean
ชนิดข้อมูล obj = object
ชนิดข้อมูล newArray = object

ความแตกต่างสำคัญ: Pass by Value vs Pass by Reference


// Primitive: Pass by Value (คัดลอกค่า)
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 (ไม่เปลี่ยน)

// Non-Primitive: Pass by Reference (อ้างอิงที่อยู่หน่วยความจำเดียวกัน)
let obj1 = { name: "John" };
let obj2 = obj1;
obj2.name = "David";
console.log(obj1.name); // "David" (เปลี่ยนไปด้วย!)

วิธี Copy Object จริง (Deep/Shallow Clone)


// Shallow clone
const clone1 = { ...obj1 };
const clone2 = Object.assign({}, obj1);

// Deep clone (สำหรับ nested object)
const clone3 = JSON.parse(JSON.stringify(obj1));
// หรือ structuredClone() (modern browsers)
const clone4 = structuredClone(obj1);