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

สร้าง Set ใน JavaScript: คลาส MySet และ ES6 Set


สร้างคลาส MySet กันไม่ให้ซ่อน Set class จริงของ JS สร้าง container object เก็บค่าที่เพิ่ม และ display function พิมพ์ set

ตัวอย่าง

class MySet { 
  constructor() { 
    this.container = {}; 
  } 
  display() { 
    console.log(this.container); 
  } 
}

ใน ES6 สร้าง set โดยตรงด้วย Set class:

ตัวอย่าง

const set1 = new Set(); 
const set2 = new Set([1, 2, 5, 6]);

ตรวจสอบสมาชิก (Membership)

เมธอด has ตรวจสอบว่าค่ามีใน set หรือไม่ ใช้ Object.hasOwnProperty ตัวอย่าง:

ตัวอย่าง

has(val) { 
  return this.container.hasOwnProperty(val); 
}

ใน ES6 Sets ใช้ has โดยตรง:

ตัวอย่าง

const testSet = new Set([1, 2, 5, 6]); 
console.log(testSet.has(5)); 
console.log(testSet.has(20)); 
console.log(testSet.has(1));

ผลลัพธ์

จะได้ผลลัพธ์:

True False True