563 words
3 minutes
Method | JavaScript
2024-11-22

Method คืออะไรกันนะ 😎 ?#

หลายๆ คนอาจจะเคยได้ยินคำว่า Method มาบ้าง แต่อาจจะยังไม่เข้าใจว่า Method คืออะไรกันแน่ วันนี้เราจะมาทำความรู้จักกับเจ้า Method กันเลย !

  • Method คือฟังก์ชันที่เป็น property ของวัตถุ (object) ซึ่งสามารถเรียกใช้งานได้ผ่านวัตถุนั้นๆ โดยทั่วไป Method มักถูกใช้ในการจัดการหรือทำงานบางอย่างที่เกี่ยวข้องกับข้อมูลหรือสถานะของวัตถุที่มันเป็นส่วนหนึ่ง

  • วัตถุ (Object) ใน JavaScript เป็นคอนเทนเนอร์ที่มีคุณสมบัติ (properties) และเมธอด (methods) ซึ่งเมธอดเหล่านี้เป็นฟังก์ชันที่สามารถเรียกใช้งานได้ผ่านวัตถุนั้นๆ เพื่อดำเนินการหรือคำนวณบางอย่าง

  1. การกำหนด Method ใน Object
const myObject = {
    name: "Gun",
    sayHello: function() {
        console.log("Hello! My name is " + this.name);
    }
};
myObject.sayHello(); // Output: "Hello! My name is Gun"
  • sayHello ในตัวอย่างข้างต้นเป็น method ที่อยู่ใน object myObject
  • คำว่า this หมายถึง object ที่ method นั้นถูกเรียกใช้งานอยู่ เช่น myObject
  1. การกำหนด Method แบบย่อ (ES6+)
const myObject = {
    name: "Gun",
    sayHello() {
        console.log("Hello! My name is " + this.name);
    }
};
myObject.sayHello(); // Output: "Hello! My name is Gun"
  1. Method ใน Class Method ยังสามารถกำหนดได้ใน Class เพื่อใช้กับ instance ของ Class นั้นๆ :
class Person {
    constructor(name) {
        this.name = name;
    }

    sayHello() {
        console.log(`Hello! My name is ${this.name}`);
    }
}

const person = new Person("Roger");
person.sayHello(); // Output: "Hello! My name is Roger"
สรุปสั้นๆ

Method เป็น Function ที่ผูกอยู่กับ Object ใช้ในการทำงานเฉพาะกับข้อมูลของObjectหรือเพื่ออำนวยความสะดวกในการจัดการข้อมูลในโปรแกรม การใช้งาน method ช่วยเพิ่มความสามารถของวัตถุและทำให้โค้ดมีโครงสร้างที่ชัดเจนมากขึ้น


Method แบบ Built-in ของ JavaScript#

JavaScript มี method ที่มาพร้อมกับ object ในตัว เช่น:

  • String methods : toUpperCase(), toLowerCase(), trim(), slice()
  • Array methods : push(), pop(), map(), filter(), reduce()
  • Object methods : keys(), values(), entries()
  • Date methods : getFullYear(), getMonth(), getDay()
const text = "Hello World";
console.log(text.toUpperCase()); // Output: "HELLO WORLD"

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]

.map Method ใน JavaScript คืออะไร 🗺 ?#

ใน JavaScript, .map() เป็น method ของ Array ที่ใช้สำหรับ สร้าง array ใหม่ โดยการเรียกใช้งานฟังก์ชันที่กำหนดบนแต่ละ element ใน array ที่มีอยู่เดิม โดยไม่เปลี่ยนแปลง array ต้นฉบับ (immutable)

คุณสมบัติของ .map()#

  1. .map() จะ วนลูป ผ่านทุก element ของ array
  2. แต่ละ element จะถูกส่งไปที่ฟังก์ชัน callback ที่กำหนด
  3. ฟังก์ชัน callback จะต้อง return ค่าที่เปลี่ยนแปลง ซึ่งจะกลายเป็น element ใหม่ใน array ใหม่
  4. ผลลัพธ์จะเป็น array ใหม่ ที่มีจำนวน element เท่ากับ array ต้นฉบับ

รูปแบบการใช้งาน .map()#

const newArray = array.map(callback(currentValue, index, array));

Parameter ของ .map()

  1. callback: ฟังก์ชันที่จะถูกเรียกใช้กับแต่ละ element
    • currentValue: ค่าของ element ปัจจุบันที่กำลังประมวลผล
    • index (optional): ดัชนี (index) ของ element ปัจจุบัน
    • array (optional): Array ต้นฉบับ
  2. thisArg (optional): ใช้สำหรับกำหนดค่า this ในฟังก์ชัน callback (ถ้าต้องการ)

ตัวอย่างการใช้งาน .map()#

  1. การเปลี่ยนค่าใน Array
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);

console.log(doubled); // Output: [2, 4, 6, 8]
console.log(numbers); // Output: [1, 2, 3, 4] (ไม่เปลี่ยนแปลง)
  1. การแปลงข้อมูลใน Array
const names = ["Alice", "Bob", "Charlie"];
const upperCaseNames = names.map(name => name.toUpperCase());

console.log(upperCaseNames); // Output: ["ALICE", "BOB", "CHARLIE"]
  1. ใช้ index ใน callback
const numbers = [10, 20, 30];
const withIndex = numbers.map((num, index) => `Index ${index}: ${num}`);

console.log(withIndex);
// Output: ["Index 0: 10", "Index 1: 20", "Index 2: 30"]
  1. การจัดการกับ object ใน Array
const users = [
  { id: 1, name: "Gun" },
  { id: 2, name: "Roger" },
  { id: 3, name: "Khunlambo" }
];

const userNames = users.map(user => user.name);

console.log(userNames); // Output: ["Gun", "Roger", "Khunlambo"]

ความแตกต่างระหว่าง .map() และ .forEach()#

.map() : สร้าง array ใหม่และ return ผลลัพธ์ .forEach() : ไม่ return อะไร ใช้เพื่อวนลูปและทำงานกับ array ต้นฉบับเท่านั้น

ตัวอย่าง:

const numbers = [1, 2, 3];

// map
const squared = numbers.map(num => num ** 2);
console.log(squared); // [1, 4, 9]

// forEach
numbers.forEach(num => console.log(num ** 2)); // แค่แสดงผล 1, 4, 9
ในการใช้ .map ทั้ง 2 แบบนี้ต่างกันยังไง
  • data.map(()=>()) และ data.map(()=>{})
  1. data.map(() => ())
    • วงเล็บกลม ( ) หมายถึงการ return ค่าทันที ใน arrow function
    • ตัวอย่าง :
    const data = [1, 2, 3];
    const result = data.map((item) => item * 2); // Return ทันที
    console.log(result); // [2, 4, 6]
    
    • ใช้ในกรณีที่ต้องการ return ค่าผลลัพธ์ออกมาทันทีโดยไม่ต้องใช้ { }
  2. data.map(() => { })
    • วงเล็บปีกกา { } หมายถึง block body ของ arrow function
    • ถ้าต้องการ return ค่าใน block body คุณต้องใช้ return ภายในวงเล็บ { } อย่างชัดเจน
    • ตัวอย่าง :
    const data = [1, 2, 3];
    const result = data.map((item) => { 
        return item * 2; 
    }); // ใช้ return ภายใน block body
    console.log(result); // [2, 4, 6]
    
    • ใช้ในกรณีที่โค้ดภายในฟังก์ชันมีหลายบรรทัด หรือมี logic ซับซ้อน เช่น การใช้ if หรือการคำนวณเพิ่มเติม

สรุป#

.map() เป็นเครื่องมือที่ทรงพลังใน JavaScript สำหรับการ แปลง (transform) ข้อมูลใน Array ให้เป็น Array ใหม่ เหมาะสำหรับสถานการณ์ที่ต้องการสร้างผลลัพธ์ใหม่โดยไม่แก้ไขข้อมูลต้นฉบับ.

Method | JavaScript
https://astro-blog.vercel.app/posts/javascript/method/
Author
MartinCats
Published at
2024-11-22