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

เมธอด Array.prototype.values() ใน JavaScript: ดึง Iterator ของค่าอาร์เรย์

เมธอด values() ใช้สำหรับ คืนค่า Array Iterator object ที่มี ค่า (values) ของแต่ละดัชนีในอาร์เรย์

ไวยากรณ์ (Syntax)

arr.values()

ตัวอย่างการใช้งาน

ตัวอย่างที่ 1: ดึงค่าแรกด้วย next()

<!DOCTYPE html>
<html>
<body>
  <h2>Array.values() Demo</h2>
  <p>คลิกเพื่อแสดงค่าแรก...</p>
  <button onclick="display()">แสดงค่า</button>
  <p id="demo"></p>
  <script>
    function display() {
      const arr = ['p', 'q', 'r'];
      const iterator = arr.values();
      document.getElementById("demo").innerHTML = "ค่าแรก: " + iterator.next().value;
      // ผลลัพธ์: p
    }
  </script>
</body>
</html>

ตัวอย่างที่ 2: วนลูปค่าทั้งหมด

<!DOCTYPE html>
<html>
<body>
  <h2>คะแนนอันดับ - Values</h2>
  <p>คลิกเพื่อแสดงค่าทั้งหมด...</p>
  <button onclick="display()">แสดงค่า</button>
  <p id="demo"></p>
  <script>
    function display() {
      const points = ['10', '20', '30', '40', '50'];
      const iterator = points.values();
      let output = "";
      for (const val of iterator) {
        output += val + "<br>";
      }
      document.getElementById("demo").innerHTML = output;
    }
  </script>
</body>
</html>

คุณสมบัติของ Values Iterator

  • เป็น Iterable - ใช้กับ for...of, Spread Operator, Array.from()
  • ใช้งานได้ครั้งเดียว (Single-use) - หลังวนจบแล้ว Iterator หมดอายุ
  • ไม่สร้างอาร์เรย์ใหม่ในหน่วยความจำ (Lazy)
  • รองรับ next() สำหรับควบคุมแบบ Manual

การใช้งานขั้นสูง

const arr = ['a', 'b', 'c'];

// 1. แปลงเป็นอาร์เรย์
const valuesArray = [...arr.values()]; // ['a', 'b', 'c']
const valuesArray2 = Array.from(arr.values()); // ['a', 'b', 'c']

// 2. ใช้ next() แบบ Manual
const it = arr.values();
console.log(it.next()); // {value: 'a', done: false}
console.log(it.next()); // {value: 'b', done: false}
console.log(it.next()); // {value: 'c', done: false}
console.log(it.next()); // {value: undefined, done: true}

// 3. ใช้กับ Destructuring
const [first, second, ...rest] = arr.values();
console.log(first);  // 'a'
console.log(second); // 'b'
console.log(rest);   // ['c']

เปรียบเทียบ keys(), values(), entries()

เมธอดคืนค่า Iterator ของตัวอย่างผลลัพธ์
keys()ดัชนี (Index)0, 1, 2
values()ค่า (Value)'a', 'b', 'c'
entries()คู่ [Index, Value][0,'a'], [1,'b'], [2,'c']

ความแตกต่างกับ forEach/map

const arr = ['x', 'y', 'z'];

// values() - ได้ Iterator (Lazy, Single-use)
for (const v of arr.values()) { ... }

// forEach() - รันทันที, ไม่คืนค่า, ไม่หยุดกลางทางได้
arr.forEach(v => { ... });

// map() - คืนอาร์เรย์ใหม่, Eager
const newArr = arr.map(v => v.toUpperCase());

กรณีใช้งานจริง

// 1. วนลูปเฉพาะค่า (ไม่ต้องการ index)
for (const value of array.values()) { ... }

// 2. ส่งต่อ Iterator ให้ฟังก์ชันอื่น
function processValues(iterator) {
  for (const v of iterator) { ... }
}
processValues(myArray.values());

// 3. รวมกับ Set/Map
const uniqueValues = new Set(array.values());